Search code examples
carrayspointersmultidimensional-array

Is a 2D Array an Array of Pointers?


If I have:

int A[10][20];
printf("%p",A[3]);

it will print the address of A[3][0].

However, I'd like to know if this one dimensional array A[3] containing pointers really exists, or it is calculated in some way.


Solution

  • The way you have defined A means that the compiler will allocate for it a contiguous block of memory large enough to hold 10 x 20 (200) integers; see here (scroll down to "Multidimesional arrays"). As I'm sure you realize, if you were to do printf("%p", A); you would see the address of the beginning of that allocated block.

    Now, when the compiler sees the expression A[3], it will add what it calculates as the necessary amount of "integer sizes" to the base address (that of A, or A[0][0]); in this case, it will add "3" (the index specified) multiplied by the combined size of all the other dimensions (in this case, there's only one, which is 20).

    So, in your case, there is no actual array of pointers; just a memory block that the compiler can interpret according to how you described any part(s) of it.

    However, in a more versatile approach, one can actually define a 2D array in terms of an actual array of pointers, like so:

    int **A;
    A = malloc(10 * sizeof(int*));
    for (int n = 0; n < 10; ++n) A[n] = malloc(20 * sizeof(int));
    

    In this case, using printf("%p",A[3]); would still be valid, but it would give a very different offset value from printf("%p",A); or printf("%p",A[0]);.

    It's also, perhaps, worth noting that, even though these two different declarations for A can both resolve an individual element through an expression like A[i][j] (but the compiler would evaluate the addresses differently), there is here scope for major confusion! When, for example, passing such an array to a function: if the function expects data allocated in the second form, and you give it an array defined in the first form (and vice versa), you're gonna get major undefined behaviour .