1

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.

Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29
Krippkrupp
  • 184
  • 1
  • 2
  • 12
  • 1
    Check out `strcpy()`. Also don't expect to be able to store a string of length 4 (+ one trailing NULL) in an array of 3 chars. Or simply `return "test";` (you'll have to return a `const char *` then.) – TypeIA Mar 08 '14 at 12:25
  • 2
    `return strcpy(malloc(sizeof(char) * 5), "test");` – Grijesh Chauhan Mar 08 '14 at 12:27

2 Answers2

3

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;
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
1

If you are not going to change the chars 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.

Community
  • 1
  • 1
Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29
  • 1
    This works, but returned the buffer (or "array" if you want) wont be modifyable. `char *p = Add() ; p[0] = 'A'; ` will crash the program. – Jabberwocky Mar 08 '14 at 12:39
  • 1
    @MichaelWalz hence the prerequisite *"if you are not going to change ..."*, but it wouldn't be bad to re-warn about that particular and important matter. – Utkan Gezer Mar 08 '14 at 12:41