[英]Invalid output in `int` array
I am trying to learn pointers and I just encountered a situation I do not understand. 我正在努力学习指针,我刚遇到一个我不明白的情况。
int main()
{
int num[3][2]={3,6,9,12,15,18};
printf("%d %d",*(num+1)[1],**(num+2));
}
As per what I have learnt the output should be : 据我所知,输出应该是:
12 15
but actually it is: 但实际上它是:
15 15
Why? 为什么? Please clarify as to how things are calculated here as what I think is first
*(num+1)
get calculated and point to the 1st one ie {9,12}
and then [1]
should dereference to first element ie 12
. 请详细说明如何计算事物,我认为首先是
*(num+1)
计算并指向第一个,即{9,12}
,然后[1]
应该取消引用第一个元素,即12
。
I am using GCC compiler. 我正在使用GCC编译器。
In your data, 在您的数据中,
int num[3][2]={3,6,9,12,15,18};
equivalent to: 相当于:
int num[3][2]={{3,6},{9,12},{15,18}};
ie 即
num[0][0] = 3
num[0][1] = 6
num[1][0] = 9
num[1][1] = 12
num[2][0] = 15
num[2][1] = 18
thus, 从而,
*(num+1)[1]
= *(*(num+1+1))
= num[2][0]
=15
and, 和,
**(num+2))
= num[2][0]
=15
Array subscript []
operator has higher precedence than dereference operator *
. 数组下标
[]
运算符的优先级高于解除引用运算符*
。
This means the expression *(num+1)[1]
is equivalent to *((num+1)[1])
这意味着表达式
*(num+1)[1]
相当于*((num+1)[1])
And if we take it apart 如果我们把它拆开
*(*((num+1)+1))
*(*(num+2))
*(num[2])
num[2][0]
See C Operator Precedence, []
is processed before *
参见C运算符优先级,
[]
在*
之前处理
That means 这意味着
(num+1)[1]
*((num+1)+1)
*(num+2)
Together with the additional *
(not written in my example), 加上附加
*
(不是我的例子中写的),
it becomes the same as the second thing. 它变成了第二件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.