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:
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:
you can use a static array in your method, to avoid lose of your array when your function ends :
}
Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.
Including "string.h" makes things easier. An easier way to tackle your problem is:
If you want to return a
char*
from a function, make sure youmalloc()
it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.change it to