对于数组,为什么会出现a [5] == 5 [a]? [英] With arrays, why is it the case that a[5] == 5[a]?

查看:86
本文介绍了对于数组,为什么会出现a [5] == 5 [a]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如Joel在 Stack Overflow播客#34 中在解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆