Return char[]/string from a function [duplicate]
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 want to return a char*
from a function, make sure you malloc()
it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.
change it to
char* createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3 * sizeof(char));
if(str == NULL) return NULL;
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
you can use a static array in your method, to avoid lose of your array when your function ends :
char * createStr()
{
char char1= 'm';
char char2= 'y';
static char str[3];
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)
char* charP = createStr();
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.