Pointers and Multidimensional Arrays

C allows multidimensional arrays, lays them out in memory as contiguous locations, and does more behind the scenes address arithmetic. Consider a 2-dimensional array.

int arr[ 3 ][ 3 ] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

The compiler treats a 2 dimensional array as an array of arrays. As you know, an array name is a pointer to the first element within the array. So, arr points to the first 3-element array, which is actually the first row (i.e., row 0) of the two-dimensional array. Similarly, (arr + 1) points to the second 3-element array (i.e., row 1) and so on. The value of this pointer, *(arr + 1), refers to the entire row. Since row 1 is a one-dimensional array, (arr + 1) is actually a pointer to the first element in row 1. Now add 2 to this pointer. Hence, (*(arr + 1) + 2) is a pointer to element 2 (i.e., the third element) in row 1. The value of this pointer, *(*(arr + 1) + 2), refers to the element in column 2 of row 1.

These relationships are illustrated below:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: