Question:
What's wrong with this C++ code?
?
2011-02-21 18:10:07 UTC
char* strnrev(char* str, int n) {
// REQ: str is a non-empty, NULL-terminated string,
// n is less than or equal to the length of str
// EFF: Reverses first n characters of str, returning the result
char result[n+1];
char* ptr = result;
for (int i = n; i > 0; i--)
*ptr++ = str[i];
result[n] = '\0';
return result;
}

The compiler gives me this error: 27: warning: address of local variable âresultâ returned

What's wrong?
Three answers:
Pencil
2011-02-21 18:45:19 UTC
I agree with the above two posters...



When you call a function it's pretty much like creating a planet... when the function returns, the return value is the one person who escapes the planet before it explodes... that person can go wherever you want them to go in your program. But if instead of the person, you return the address to that person's house, it doesn't do you much good since the planet has exploded into dust.



Also, if you include the library, you can use strings, which are much cooler than character strings and character pointers, though, they take some getting used to at first.
Ratchetr
2011-02-22 02:25:52 UTC
The previous answer got it right, when you return the address of a local (stack) variable, you are essentially returning a pointer to garbage. Three is no guarantee that what you put in that memory will still be there when the caller uses it.



Why are you using char *'s in C++? This is a function that should be returning a string. One of the good things about C++ is that you fall into far fewer tarpits of functions returning pointers to memory that isn't valid when you need it.
Juniocarl :[
2011-02-22 02:19:07 UTC
You are returning the memory address of a local variable. When the function ends, this variable is destroyed. You should reserve dynamic memory with malloc function, or recieve a pointer to a string you had declarated in the main function.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...