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();
file is a stack variable in ListFiles() and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid. If you want to return a string, you should allocate it on the heap, return it, use it, then free it once you're done using it.
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With