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.
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.");
}
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.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.