Matt Pennington Matt Pennington - 3 months ago 42
C Question

Pass char[] as reference in c

I am trying to pass a char[] to a function and mutate it. The following code compiles and works as expected for my test case, but I get some compiler warnings and I can't figure out how to resolve them.

Code:
#include
#include

#define MAX_STRING_SIZE 100

void strOp(char **someString) {
snprintf( someString, sizeof(someString), "HELLO");
}

int main() {
char myString[MAX_STRING_SIZE];
strOp(&myString);
printf("%s\n", myString);
return 0;
}


Warnings:

echoecho.c: In function ‘strOp’:
echoecho.c:18:3: warning: passing argument 1 of ‘snprintf’ from incompatible pointer type [enabled by default]
snprintf( someString, sizeof(someString), "HELLO");
^
In file included from echoecho.c:12:0:
/usr/include/stdio.h:386:12: note: expected ‘char * __restrict__’ but argument is of type ‘char **’
extern int snprintf (char *__restrict __s, size_t __maxlen,
^
echoecho.c: In function ‘main’:
echoecho.c:23:3: warning: passing argument 1 of ‘strOp’ from incompatible pointer type [enabled by default]
strOp(&myString);
^
echoecho.c:17:6: note: expected ‘char **’ but argument is of type ‘char (*)[100]’
void strOp(char **someString) {


I've tried a few combinations of using *, *[], and ** and have found a few that work but there are always warnings. Any ideas how to clean this up?

Answer

pass pointers to char

try

#include<cstdlib>
#include<string.h>
#define MAX_STRING_SIZE 100

void strOp(char *someString) {
snprintf( someString,MAX_STRING_SIZE, "HELLO");
}

 int main() {
 char myString[MAX_STRING_SIZE];
 strOp(myString);
 printf("%s\n", myString);
 return 0;  
 }