对于数组,为什么会出现a [5] == 5 [a]? [英] With arrays, why is it the case that a[5] == 5[a]?
问题描述
C标准对[]
运算符的定义如下:
a[b] == *(a + b)
因此,a[5]
的计算结果为:
*(a + 5)
和5[a]
的计算结果为:
*(5 + a)
a
是指向数组第一个元素的指针. a[5]
是距离a
的5个元素的值,它与*(a + 5)
相同,并且从小学数学我们知道它们是相等的(加法是Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]
?
The C standard defines the []
operator as follows:
a[b] == *(a + b)
Therefore a[5]
will evaluate to:
*(a + 5)
and 5[a]
will evaluate to:
*(5 + a)
a
is a pointer to the first element of the array. a[5]
is the value that's 5 elements further from a
, which is the same as *(a + 5)
, and from elementary school math we know those are equal (addition is commutative).
这篇关于对于数组,为什么会出现a [5] == 5 [a]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!