title: How to pass pointer to function and dynamically allocate memory within function C++
body: <p>I'm trying to declare a pointer and pass that pointer to a function where memory is allocated.  Here is a minimal example:</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  void alloc_mem(int &amp;size, double *x);
  
  int main()
  {
  
          double *X;
          int imax;
  
          alloc_mem(imax, X);
  
          cout &lt;&lt; "imax = " &lt;&lt; imax &lt;&lt; endl;
          for (int i = 0; i &lt; imax; i++) {
                  cout &lt;&lt; "X = " &lt;&lt; X[i] &lt;&lt; endl;
          }
  
          delete[]X;
          return 0;
  
  }
  
  void alloc_mem(int &amp;size, double *x)
  {
  
          size = 10;
          x = new double[size];
          for (int i = 0; i &lt; size; i++) {
                  x[i] = (double)i;
          }
  
  }
  </code></pre>
  
  <p>This code compiles, but I get a segmentation fault when I try to print out the values of X.  I know that I'm not passing the variable into the function correctly, but I'm not sure how to do it.  I believe that I'm operating on a copy of x.</p>
  
  <p>Also, this code was written to reproduce an issue I'm having in a much larger code.</p>