Im fairly new to coding in C and currently im trying to create a function that returns a c string/char array and assigning to a variable.
So far, ive observed that returning a char * is the most common solution. So i tried:
char* createStr() {
char char1= 'm';
char char2= 'y';
char str[3];
str[0] = char1;
str[1] = char2;
str[2] = '\0';
char* cp = str;
return cp;
}
My question is how do I use this returned char*
and assign the char array it points to, to a char[] variable?
Ive tried (all led to noob-drowning errors):
char* charP = createStr();
char myStr[3] = &createStr();
char* charP = *createStr();
Including "string.h" makes things easier. An easier way to tackle your problem is:
#include <string.h>
char* createStr(){
static char str[20] = "my";
return str;
}
int main(){
char a[20];
strcpy(a,createStr()); //this will copy the returned value of createStr() into a[]
printf("%s",a);
return 0;
}
you can use a static array in your method, to avoid lose of your array when your function ends :
char * createStr()
{
char char1= 'm';
char char2= 'y';
static char str[3];
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)
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] = '\0';
return str;
}
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.
Source: Stackoverflow.com