title: C++ - Segmentation Fault - Dynamic array
body: <p>I have been trying to implement a dynamic array in C++ and got some troubles with the pointer references.</p>
  
  <p>With the following code, I got a segmentation fault.</p>
  
  <p>If I use the array and the size as global variables, the application works. I know I could do it, but I would like to know why it is not working.
  I think I am losing the pointer array pointer reference, but I don`t know how to mantain it inside the method.</p>
  
  <p>I don't want to use STL containers like vector.</p>
  
  <p>Thanks for your help.</p>
  
  <pre><code>void addElement(int newElement, unsigned int * array, int&amp; size ){
      /* create a temp array in order to copy the contents from the current array
      * it is needed because we want to increase the size of the array */
      unsigned int* temp = new unsigned int[size + 1];
  
     // copy all the data from array to temp
     for (int x=0; x &lt; size; x++){
         *(temp + x) = array[x];
     }
  
     // add the new element
     *(temp + size) = newElement;
  
     size++;
  
     // release the memory from the temp array
     delete [] array;
  
     // the temp array turn into the temp array, that contains all the elements
     array = temp;
  
  }
  
  int main(){
  
      unsigned int * array;
      int size;
  
      addElement(1, array, size);
      addElement(2, array, size);
      addElement(3, array, size);
      cout &lt;&lt; array[1];
      return 1;
  
  }
  </code></pre>