title: Difference between C and JAVA program
body: <p>I have two examples of the same program. This program has a function which creates an array and returns the pointer to array.</p>
  
  <p>First program (in C):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define N 5
  
  int* GetValues()
  {
     int items[N] = { 1, 2, 3, 4, 5 };
     return items;
  }
  
  int main(int argc, char** argv) {
  
      int *array = GetValues();    
      int i;    
      for(i = 0; i &lt; N; i++)
      {
          printf("%d\n", array[i]);
      }    
  
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>Second program (in Java):</p>
  
  <pre><code>package tests;
  
  public class Tests {
  
      public static int[] foo() {        
          int array[] = { 1, 2, 3, 4, 5 };
          return array;        
      }
  
      public static void main(String[] args) {        
          int[] array = foo();        
          for(int i = 0; i &lt; array.length; i++) {
              System.out.println(array[i]);
          }                
      }
  }
  </code></pre>
  
  <blockquote>
    <p>The result of the Java program is the following: 1, 2, 3, 4, 5</p>
    
    <p>The result of the C program is the following: 1 -1075386156
    -1218492432 1 -1216747208</p>
  </blockquote>
  
  <p>Why do we have that different results? My version is the following.</p>
  
  <p>In C program inside of the GetValues() function the items[] local array will be created and initialized. The return instraction will return the pointer to begining of the array, but this array will be allocated at the LOCAL memory of that function. When the last instruction of the GetValues() function will be invoked the local memory will be destroyed. In this case we can't predict what data are stored there and we dont know what will print the <code>printf("%d\n", array[i])</code> instruction (no wonder, the memory has been destroyed and values as well).</p>
  
  <p>In java program we have the following situation. Arrays in JAVA are objects. Objects in java are storing in heap. So, after executing <code>foo()</code> method the object <code>array</code> will be created and puted to the heap. After executing method local variables will be cleaned, but our pointer to <code>array</code>-object is still in the heap (garbage collector will understand when this object has to be deleted), what is why we are able to print it normally.</p>
  
  <p>Am I right? Do I understand this features properly? If not can somebody correct me?
  Thanks in advance.</p>
  
  <p>P.S. Sorry for my english I hope I explained my problem more or less clear.</p>