Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Couple things:</p> <ul> <li>You need to pass the argument by reference in func: <code>void func(int ***arr) {</code></li> <li>Then change the way you free things: <code>free((*arr)[i]);</code> and <code>free(*arr);</code></li> <li>and finally change how you reassign arr: <code>*arr = destMatrix;</code></li> <li>also, don't name variables starting with a number -- it doesn't work.</li> <li>(also, you had <code>++i</code> instead of <code>i++</code> at the for loop at the end of func ) this doesn't actually matter -- see the comment below</li> </ul> <p>I debugged these issues using <a href="http://valgrind.org/docs/manual/quick-start.html#quick-start.intro" rel="nofollow" title="Valgrind">Valgrind</a>, check it out.</p> <p>Working code is below:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define N 10 ////////////////////////////////////////////////////////////////////////// void func(int ***arr) { int **destMatrix = NULL; destMatrix = malloc(N * sizeof(int *)); if ((destMatrix == NULL)) { fprintf(stderr, "out of memory\n"); exit(2); } int i; for (i = 0; i &lt; N; i++) { destMatrix[i] = malloc(N * sizeof(int)); if (destMatrix[i] == NULL) { fprintf(stderr, "out of memory\n"); exit(2); } } for(i = 0; i &lt; N; i++) { free((*arr)[i]); } free(*arr); *arr = destMatrix; } ////////////////////////////////////////////////////////////////////////// int main() { int **tdArr = malloc(N * sizeof(int *)); if (tdArr== NULL) { fprintf(stderr, "out of memory\n"); exit(2); } int i; for (i = 0; i &lt; N; i++) { tdArr[i] = malloc(N * sizeof(int)); if (tdArr[i] == NULL) { fprintf(stderr, "out of memory\n"); exit(2); } } func(&amp;tdArr); // try to print new array, does not get access violation //assign numbers 0-99 int j; for (i=0; i&lt;N; i++){ for (j=0; j&lt;N; j++){ tdArr[i][j] = i*10+j; } } //print numbers for (i=0; i&lt;N; i++){ for (j=0; j&lt;N; j++){ printf("%d\n", tdArr[i][j]); } } //free internal arrays for (i=0; i&lt;N; i++){ free(tdArr[i]); } //free outer array free(tdArr); return 0; } </code></pre>
 

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