title: Returning an array of pointers from a function
body: <p>I am trying to print the integer value of each character in a given string using a function. When I pass a string to this function, it converts each character in the given string to an integer and then saves it to a result array. I have also created an array of pointers which will hold the address of each character's corresponding integer. But when I return this array of pointers, I am not able to print all integer values correctly.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int *c2i(char *str); 
  
  int main(){
  
      char s[20];
      int *p, i;
      printf("Enter your string:\n");
      scanf("%s", s);
      p=c2i(s);
      for(i=0; i&lt;4; i++){
          printf("\n%d\t%d\n", *p, p);
          p++;
      }
  
      return 0;
  }
  
  int *c2i(char *str){
  
      int i=0, result[20], *ptr[20];
  
      while(*(str+i)!='\0'){
          result[i]=*(str+i) &amp; 0xff;
          ptr[i]=&amp;result[i];
          i++;
      }
      printf("%d %d %d %d %d %d %d %d", *ptr[0], *ptr[1], *ptr[2], *ptr[3], ptr[0], ptr[1], ptr[2], ptr[3]);
  
      return *ptr;
  }
  </code></pre>
  
  <p>I have included many <strong><code>printf</code></strong> statements just for debugging purposes. The output of the program when I try to run the code above is:</p>
  
  <blockquote>
    <p>Enter your string:</p>
    
    <p>abcd</p>
    
    <p>97 98 99 100 6356588 6356592 6356596 6356600</p>
    
    <p>97                  6356588</p>
    
    <p>1999382056          6356592</p>
    
    <p>20                  6356596</p>
    
    <p>1                   6356600</p>
  </blockquote>
  
  <p>I am only getting the first value correctly when I print it in the <strong><code>main()</code></strong> function. When I increment the pointer and try to print the next values, I am getting garbage results. I can see that the address is the same but the values have been corrupted. What am I doing wrong here?</p>