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

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

问题描述

正如 Joel 在 Stack Overflow 播客 #34 中指出的那样,C 编程语言(又名:K & R),有提到这个C 中数组的属性:a[5] == 5[a]

As Joel points out in 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 说是因为指针运算,但我还是不明白.为什么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]?

推荐答案

C 标准定义了 [] 操作符如下:

The C standard defines the [] operator as follows:

a[b] == *(a + b)

因此 a[5] 将评估为:

*(a + 5)

5[a] 将评估为:

*(5 + a)

a 是指向数组第一个元素的指针.a[5] 是距离 a 5 元素 的值,与 *(a + 5)<相同/code>,从小学数学我们知道它们是相等的(加法是可交换).

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天全站免登陆