Im fairly new to coding in C and currently im trying to create a function that returns a c string/char array and assigning to a variable.
So far, ive observed that returning a char * is the most common solution. So i tried:
char* createStr() {
char char1= 'm';
char char2= 'y';
char str[3];
str[0] = char1;
str[1] = char2;
str[2] = '\0';
char* cp = str;
return cp;
}
My question is how do I use this returned char*
and assign the char array it points to, to a char[] variable?
Ive tried (all led to noob-drowning errors):
char* charP = createStr();
char myStr[3] = &createStr();
char* charP = *createStr();
Notice you're not dynamically allocating the variable, which pretty much means the data inside str
, in your function, will be lost by the end of the function.
You should have:
char * createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3);
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:
char *returned_str = createStr();
It worths mentioning that the returned value must be freed to prevent memory leaks.
char *returned_str = createStr();
//doSomething
...
free(returned_str);