Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What's biting you here is C's (and C++'s) lack of by-reference argument passing. The <code>a</code> in <code>main()</code> is distinct from the <code>a</code> in <code>func()</code>:</p> <ol> <li><code>a</code> is declared in <code>main</code>.</li> <li><code>a</code> is passed by value (because there's no other way) to <code>func</code>.</li> <li>The <code>a</code> in <code>func</code> is assigned to.</li> <li><code>func</code> returns. Its <code>a</code> is destroyed (leaking memory), and <code>main</code>'s <code>a</code> is left uninitialised.</li> <li>???</li> <li><code>main</code> tries to use <code>a</code>. <strong><em>Segfault!</em></strong></li> </ol> <p>There are a few possible solutions here:</p> <ol> <li><p>Do it the classic C way: pass a pointer to the value. In this case, the parameter will be <code>int ***a</code>, which is gettng a little ridiculous, but whatever.</p> <pre><code>void func(int ***a, int x, int y) { *a = new int*[x]; for (int i=0; i&lt;x; i++) (*a)[i] = new int[y]; } int main(int argc, char **argv) { ... int **a; func(&amp;a, 2, 3); ... } </code></pre></li> <li><p>Do it the C++ way: pass a reference.</p> <pre><code>void func(int **&amp;a, int x, int y) { // ^ // This is the only change. Neat! </code></pre></li> <li><p>Do it the proper (in my opinion) way: return a value from the function, and initialise the array from that.</p> <pre><code>int **func(int x, int y) { int **a = new int*[x]; // EDIT: Fixed stupid typo bug // existing code return a; } int main(int argc, char **argv) { ... int **a = func(2, 3); ... } </code></pre></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload