2D array and pointer in C - how to access elements?

前端 未结 5 1345
小蘑菇
小蘑菇 2020-12-15 11:44

I have an example involving a pointer to a 2D array. Can someone help me understand what is going on in this example?

int main()
{

    int i = 0, j=0, sum0         


        
5条回答
  •  感动是毒
    2020-12-15 12:43

    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. where 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.

提交回复
热议问题