title: Returning pointers from function as static variable
body: <p>I'm studying C and reading <a href="http://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm" rel="nofollow">this</a></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;time.h&gt;
  
  /* function to generate and retrun random numbers. */
  int * getRandom( ) {
  
     static int  r[10];
     int i;
  
     /* set the seed */
     srand( (unsigned)time( NULL ) );
  
     for ( i = 0; i &lt; 10; ++i) {
        r[i] = rand();
        printf("%d\n", r[i] );
     }
  
     return r;
  }
  
  /* main function to call above defined function */
  int main () {
  
     /* a pointer to an int */
     int *p;
     int i;
  
     p = getRandom();
  
     for ( i = 0; i &lt; 10; i++ ) {
        printf("*(p + [%d]) : %d\n", i, *(p + i) );
     }
  
     return 0;
  }
  </code></pre>
  
  <p>The article explains that, since a pointer declared in a function is a local variable, hence it has to be defined as 'static'. (line 7, variable r)</p>
  
  <p>There are three points I'm concerned.</p>
  
  <ul>
  <li><p>Firstly, "static int r[10]" declares that they want to create an int array of size 10. When it's returned from the getRandom function with "return r", the function actually returns <strong>the address</strong> of the first member of r[10], or <strong>the pointer</strong> to the first address of r[10]?</p></li>
  <li><p>Secondly, in main function, p = getRandom() means the address or pointer returned from getRandom() is assign to pointer p. Eventhough r will poof as soon as getRandom() stops working, the address would have been already assigned to p. So, why is it needed to be declared as static? </p>
  
  <p>Or getRandom() returns address to the pointer pointing to r[10], hence when disappear, p would point to empty address not to r[10]?</p>
  
  <p>Or, not only pointer to r, but also r[10] array would disappear when getRandom() stops, so it's needed to be static?</p></li>
  <li><p>Thirdly, is it correct that, variables in any function declared without malloc would be stored as stack memory?</p></li>
  </ul>