Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return char[]/string from a function [duplicate]

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):

  1. char* charP = createStr();
  2. char myStr[3] = &createStr();
  3. char* charP = *createStr();
like image 792
user1993177 Avatar asked Jan 19 '13 17:01

user1993177


People also ask

How do I return a character pointer?

file is a stack variable in ListFiles() and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid. If you want to return a string, you should allocate it on the heap, return it, use it, then free it once you're done using it.

Can I return a char array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.


1 Answers

Notice you're 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] = '\0';      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); 
like image 128
Rubens Avatar answered Oct 16 '22 05:10

Rubens