Reputation: 194
I've searched and found dozens of solutions to returning a character array from a function, but none of them works. I'm sure this must be viable in C. Basicly, this is what I want to do.
char* Add( )
{
char *returnValue = (char *) malloc( sizeof(char) * 3 );
returnValue = "test"; //This doesn't work. I'm not at all interrested in doing returnValue[0] = 't', returnValue[1] = 'e', etc.
return returnValue;
}
I hope you understand what I want to do here.
Upvotes: 1
Views: 8300
Reputation: 3069
If you are not going to change the char
s pointed by the returnValue
pointer ever in your programme, you can make it as simple as:
char* Add( )
{
return "test";
}
This function creates allocates a memory block, fills it with the following:
't' 'e' 's' 't' '\0'
And then returns the address off the first element 't'
. The memory allocated for the string literal will be preserved until the end of the programme, as per the answer there.
Upvotes: 1
Reputation: 107739
The assignment returnValue = "test"
makes the returnValue
variable point to a different space in memory. It doesn't affect the space that you just allocated by malloc
; furthermore, since this space isn't referenced any more, it will remain allocated but unused until your program exits.
You need to copy the string into the space that you just allocated. There's a function for that in the standard library: strcpy
(declared in <string.h>
). Note that strcpy
doesn't check that the destination buffer is large enough, you need to ensure that before calling it.
The string you want to return is 4 bytes long, plus the null terminator makes 5. So you need to allocate (at least) 5 bytes, not 3.
char* Add()
{
char *returnValue = malloc(sizeof(char) * 5);
strcpy(returnValue, "test");
return returnValue;
}
Upvotes: 3