0

How do I return a char array from a function?

has the following code in the answers:

void testfunc(char* outStr){
  char str[10];
  for(int i=0; i < 10; ++i){
    outStr[i] = str[i];
  }
}

int main(){
  char myStr[10];
  testfunc(myStr);
  // myStr is now filled
}

Since I will be using an Arduino where memory is precious I dont want a "temporary variable" for storing some string and then copying it over. I also don't want the function to return anything. I want to use the idea above and do something like:

 void testfunc(char* outStr){
     outStr="Hi there.";
  }

int main(){
  char myStr[10];
  testfunc(myStr);

}

However, in this case myStr is empty!

Why doesn't this work? How do I fix it?

(I'm relatively new to C, and do have a basic understanding of pointers)

Thanks.

Community
  • 1
  • 1
k29
  • 641
  • 6
  • 26
  • Use strcpy(). Not adding an argument that passes the size of the passed char[] is a mistake. – Hans Passant Nov 06 '13 at 22:12
  • Can you please elaborate on passing the size of the char[]. If I'm not using its size then why pass it? – k29 Nov 06 '13 at 22:16
  • You say that you aren't using the size, but to copy the string `"Hi there."` you need to somehow know that the array pointed to by the parameter is at least 10 bytes. If that number 10 is part of the documentation of your function then you can just about get away with it. But that's an unusual situation: it's more common that the caller needs to tell you the size of the array so that you can avoid overrunning it. – Steve Jessop Nov 06 '13 at 22:18
  • Thanks! Before you posted a reply I also found this http://stackoverflow.com/questions/6638729/when-do-we-need-to-pass-the-size-of-array-as-a-parameter – k29 Nov 06 '13 at 22:19

2 Answers2

1

Why doesn't this work?

void testfunc(char* outStr){
     outStr="Hi there.";
 }

You have:

testfunc(myStr);

When testfunc is called, outStr is assigned the address of the first element of myStr. But in the testfunc function, you overwrite outStr and it now points to a string literal. You are only modifying ouStr, not myStr.

How do I fix it?

To copy a string, use strcpy function (or its secure sister strncpy):

void testfunc(char* outStr){
     strcpy(ouStr, "Hi there."); 
 }
ouah
  • 142,963
  • 15
  • 272
  • 331
0

If you want memory reuse - and this is a dangerous place, has you must take really good care about allocation/deallocation responsibility, you should use pointer to string, ie:

#define STATIC_STRING "Hi there"

void testfunc(char**outStr){
    *outStr=STATIC_STRING;
}

int main(){
   char*myStr;
   testfunc(&myStr);
   //From now on, myStr is a string using preallocated memory.
}
LS_ᴅᴇᴠ
  • 10,823
  • 1
  • 23
  • 46