Function
char* getConnectDetail(int starting){
String data;
for(int i=0;i< 1024 ;i++) {
if(EEPROM.read(i+starting) != 0){
data += char(EEPROM.read(i+starting));
}
}
int str_len = data.length() + 1;
char char_array[str_len];
data.toCharArray(char_array, str_len);
return char_array;
}
When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it. I just want to know whats wrong with my returning method.
1 Answer 1
char char_array[str_len];
is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.
If the caller creates data
and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make data
a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.
-
Good answer. Another alternative is to have the function malloc memory for the array and return that. Then the caller would be responsible for freeing it when it was done with it.Duncan C– Duncan C2019年08月18日 19:45:45 +00:00Commented Aug 18, 2019 at 19:45
-
Also note that the OPs function will have to return the length of the string array somehow.Duncan C– Duncan C2019年08月18日 19:46:58 +00:00Commented Aug 18, 2019 at 19:46
-
Since it no longer has to return the array (caller owns it), the return value is available to return a count or error code.JRobert– JRobert2019年08月18日 22:56:08 +00:00Commented Aug 18, 2019 at 22:56
Explore related questions
See similar questions with these tags.
Arduino IDE function
... it is aC++ function