[英]Understanding C arrays and pointers
Need a little help understanding what exactly is going on in this code snippet. 需要一些帮助来了解此代码段中究竟发生了什么。 When I run the program it prints 7. 当我运行该程序时,它打印7。
#include <stdio.h>
int main() {
int a[] = {1,2,3,4,5,6,7,8,9};
int b[] = {1,2,3,4,5,6,7,8,9};
int c = 5;
int *p = a;
printf("--> %d", (c[b])[p]);
return 0;
}
I'm just a little confused when it comes to the (c[b])[p] part in the printf statement. 当涉及到printf语句中的(c [b])[p]部分时,我只是有点困惑。 Any help/explanation would be greatly appreciated. 任何帮助/解释将不胜感激。
It's a bit weird to be written that way, but the []
operator in C is commutative. 以这种方式编写有点奇怪,但C中的[]
运算符是可交换的。 That means (c[b])[p]
is the same as p[b[c]]
, which is a lot easier to understand: 这意味着(c[b])[p]
与p[b[c]]
,这更容易理解:
p[b[c]] = p[b[5]] = p[6] = a[6] = 7
Doing the same with the original expression will work too, it's just a bit weird to look at in places: 对原始表达式执行相同操作也会起作用,在某些地方查看它有点奇怪:
(c[b])[p] = (5[b])[p] = (b[5])[p]) = 6[p] = p[6] = a[6] = 7
The commutativity (if that's a word) of []
is just due to its definition - that is, a[b]
is the same as *(a + b)
, where you can see the order of a
and b
doesn't matter. []
的交换性(如果这是一个单词)仅仅是由于它的定义 - 也就是说, a[b]
与*(a + b)
,你可以看到a
和b
的顺序无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.