
Originally Posted by
Salem
In both cases, you're returning a pointer to a local variable when you do return buf;
That means your entire result string is out of scope when you get back to main.
The memory that buf occupied can be re-used for other purposes, leading to all manner of interesting effects, including apparently working.
Reverse is broken - period.
Tweaking main into giving you the apparently right answer is
voodoo.
I've programmed a lot on java and python, and for me it's very difficult to understand the C language in which you can not return a local variable without any problems.
The problem was because I was mistaken in the program! I made a debug and realized that I went beyond the array and here is the working code:
Code:
#include <stdio.h>
#include <string.h>
char * reverse(char *s, char *buf)
{
int len = strlen(s);
strcpy(buf, s);
for(int l = len; l > 0; l--) {
//printf("%i: '%c'\n", l, *s);//DEBUG
buf[l-1] = *s++;
}
return buf;
}
int main(int argc, char const *argv[])
{
char *str = "hello";
char buf[5];
printf("'%s'\n", reverse(str, buf));
str = "hel";
printf("'%s'\n", reverse(str, buf));
printf("'%s'\n", buf);
return 0;
}