I've tried the following:
char[10] testfunc()
{
char[10] str;
return str;
}
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string.
Explanation: The strchr() function is used to return a pointer to the located character if character does not occur then a null pointer is returned.
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
}
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);
A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.
Use something like this:
char *testfunc() {
char* arr = malloc(100);
strcpy(arr,"xxxx");
return arr;
}
This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.
As noted in the comment section: remember to free the memory from the caller.
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