C中的2D数组和指针-如何访问元素? [英] 2D array and pointer in C - how to access elements?
问题描述
我有一个涉及2D数组的指针的示例.有人可以帮助我了解此示例中发生的情况吗?
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=0, sum1=0;
int data[4][3] = { {23,55,50},{45,38,55},{70,43,45},{34,46,60}};
int *Ptr;
Ptr = *data; //Why is the indirection operator used here?
// Does Ptr = 23 by this assignment?
for (i=0; i<4; i++) {
sum1 = 0;
for (j = 0; j < 3; j++) {
sum1 += data[i][j];
}
if (sum1 > sum0) {
sum0 = sum1;
Ptr = *(data + i); // Seems like this statement makes Ptr
} // point one row below ... what syntax
} // can you use to access columns then?
// Is it possible to use pointer arithmetic
for (i=0; i<3; i++) // to access elements of data[i][j] that
printf("%d\n", Ptr[i]); // are not at j = 0?
return 0;
}
推荐答案
data
是2维数组,具有4行,每行具有3个元素(即4 X 3).
data
is a 2 dimentional array, which has 4 rows and each row has 3 elements (ie 4 X 3).
现在,Ptr = *data;
表示您正在将第一行的起始地址存储到指针变量Ptr
.该语句等效于Ptr = *(data + 0)
. Ptr = *(data + 1)
-这意味着我们正在分配第二行的起始地址.
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.
然后*Ptr
或*(Ptr + 0)
将为您提供所指向行的第一个元素的值.同样,*(Ptr + 1)
将为您提供该行第二个元素的值.
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.
程序中的for
循环用于标识哪一行具有其元素之和(3个元素)的最大值.一旦控件脱离该for
循环,Ptr
将指向其元素的总和最大的行,而sum0
将具有该总和的值.
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.
考虑一个数组int a[5];
,希望您知道a[0]
和0[a]
是相同的.这是因为a[0]
表示*(a+0)
,而0[a]
表示*(0 + a)
.相同的逻辑可以在二维数组中使用.
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]
与*(*(data + i) + j)
类似.我们也可以将其写为i[data][j]
.
data[i][j]
is similar to *(*(data + i) + j)
. We can write it as i[data][j]
also.
有关更多详细信息,请参阅yashwant kanetkar撰写的《理解c中的指针》一书.
For more details please refer to the book "understanding pointers in c" by yashwant kanetkar.
这篇关于C中的2D数组和指针-如何访问元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!