title: Value of Pointer is Garbage when Returned
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope">Can a local variable’s memory be accessed outside its scope?</a>  </p>
  </blockquote>
  
  
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  char* reverse(char* input) 
  {
      char b[11];
  
      for (int i=0; i&lt;11; i++)    {b[10-i]=input[i];}
      for (int u=0; u&lt;11; u++)    {cout&lt;&lt;b[u];}
      cout&lt;&lt;endl;
      return &amp;b[0];
  }
  
  int main ()
  {
       char ali[]="ali is good";
       char *a=&amp;ali[0];
       char *b=reverse(a);
  
       for (int i=0; i&lt;11; b++, i++)  
          {
              cout&lt;&lt;*b+i&lt;&lt;endl;
          }
       cout&lt;&lt;endl;
       system("pause");
       return 0;
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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>
  
  <p>P.S. this is not a HW!! I "was" a longtime programmer, shame on me for forgetting all of this.</p>
  
  <p>Any ideas?</p>