Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?
#include <iostream>
#include <string>
using namespace std;
char* reverse(char* input)
{
char b[11];
for (int i=0; i<11; i++) {b[10-i]=input[i];}
for (int u=0; u<11; u++) {cout<<b[u];}
cout<<endl;
return &b[0];
}
int main ()
{
char ali[]="ali is good";
char *a=&ali[0];
char *b=reverse(a);
for (int i=0; i<11; b++, i++)
{
cout<<*b+i<<endl;
}
cout<<endl;
system("pause");
return 0;
}
This is a simple program to reverse a string, it works well when you print the result in the function, but when passing the pointer of the string to Main then printing it, it prints garbage-like things.
Why is it strange? because if I print *b+2 or *b+5 or whatever const I like, it works well, but if I replace the const with an int in a loop like *b+i then it does not work!!
P.S. this is not a HW!! I "was" a longtime programmer, shame on me for forgetting all of this.
Any ideas?