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
data
is a 2 dimentional array, which has 4 rows and each row has 3 elements (ie 4 X 3).
Now, Ptr = *data;
means you are storing the starting address of 1st row to the pointer variable Ptr
. This statement is equivalent to Ptr = *(data + 0)
. Ptr = *(data + 1)
- this means we are assigning 2nd row's starting address.
Then *Ptr
or *(Ptr + 0)
will give you the value of the first element of the row to which is pointing. Similarly, *(Ptr + 1)
will give you the value of the second element of the row.
The for
loop in your program is used to identify which row has the maximum value of the sum of its elements (3 elements). Once the control comes out of that for
loop, Ptr
will be pointing to the row which has the maximum sum of its elements and sum0
will have the value of the sum.
Consider an array int a[5];
, I hope you know that a[0]
and 0[a]
is the same. This is because a[0]
means *(a+0)
and 0[a]
means *(0 + a)
. This same logic can be used in 2 dimensional array.
data[i][j]
is similar to *(*(data + i) + j)
. We can write it as i[data][j]
also.
For more details please refer to the book "Understanding Pointers in C" by Yashavant Kanetkar.