c – Return char[]/string from a function

c – Return char[]/string from a function

Notice youre 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] = ;

    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] = ;
    return str;
}

c – Return char[]/string from a function

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.

Leave a Reply

Your email address will not be published.