2D dynamic array in continuous memory locations (C)

2DarrayCont.c

As one can see here, we dynamically allocate a 2D array and of course de-allocate it. However, there are times, that we need to be sure that the memory locations are continuous (for example, in parallel programming). The following piece of code achieves this.
dynamic allocate 2D array continuous

int** allocate2D(int** A, const int N, const int M) {
    int i;
    int *t0;

    A = malloc(M * sizeof (int*)); /* Allocating pointers */
    t0 = malloc(N * M * sizeof (int)); /* Allocating data */
    for (i = 0; i < M; i++)
        A[i] = t0 + i * (N);

    return A;
}

void free2Darray(int** p, const int N) {
    free(p[0]);
    free(p);
}

This code is developed by me, G. Samaras.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

4 thoughts on “2D dynamic array in continuous memory locations (C)

  1. Pingback: De-allocation of a matrix.

  2. Pingback: Is it mandatory to allocate space for the pointers in arrays?

    • If we used strcmp, then this line:
      array[i] = &data[i * cols];
      would be different. Only yesterday, I realized that the comment you had made here https://gsamaras.wordpress.com/code/2d-dynamic-array-c/ was equivalent. I had forgotten it and it was a petty, because when one friend of mine needed to allocate contiguous allocation, did have a hard time figuring it out and if I had remembered your comment, it would be far more easy for him to achieve his goal!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s