How do I return a char array from a function?
You have to realize that char[10]
is similar to a char*
(see comment by @DarkDust). You are in fact returning a pointer. Now the pointer points to a variable (str
) which is destroyed as soon as you exit the function, so the pointer points to... nothing!
Usually in C, you explicitly allocate memory in this case, which won't be destroyed when the function ends:
char* testfunc()
{
char* str = malloc(10 * sizeof(char));
return str;
}
Be aware though! The memory pointed at by str
is now never destroyed. If you don't take care of this, you get something that is known as a 'memory leak'. Be sure to free()
the memory after you are done with it:
foo = testfunc();
// Do something with your foo
free(foo);
Best as an out parameter:
void testfunc(char* outStr){
char str[10];
for(int i=0; i < 10; ++i){
outStr[i] = str[i];
}
}
Called with
int main(){
char myStr[10];
testfunc(myStr);
// myStr is now filled
}