1

Hello I've never used dynamics 2-dimension array in C, so I need your help. How can I build 2-dimension array with allocating memory?

I thought about something like this :

int ** dynamic_allocate_array(int n, int m) {
    int **A = (int **) malloc(n*sizeof(int *));
    int i;
    for (i = 0; i < n; i++) {
        A[i] = (int *) malloc (m*sizeof(int));
    }
    return A;
}

But my program crushes due to allocating the memory. I need your advice!

openspace
  • 163
  • 8
  • 2
    This function looks ok. The crash is elsewhere. – Eugene Sh. Feb 14 '17 at 22:49
  • Please show the code where you invoke your function and how you use the result. Note that `A` is actually not a 2D-array like `int[n][m]`, but rather a pointer to an array of pointers to ints. – Stephan Lechner Feb 14 '17 at 22:54
  • First of all you should check if your calls to `malloc` fail – Romain Feb 14 '17 at 22:55
  • `int **` is not a 2D array and cannot represent one. If you want a 2D array, use one, there is enough material here and elsewhere, that would also simplify allocation/freeing. Also don't cast the result of `malloc`. Re your problem: provide a [mcve]. – too honest for this site Feb 14 '17 at 22:58
  • Where its crashing? inside the function? outside? + please check your malloc return value in the code – t.elazari Feb 14 '17 at 23:00
  • [DON'T CAST THE RETURN VALUE OF MALLOC](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MD XF Feb 14 '17 at 23:11

0 Answers0