随着C数组,为什么是这样一个[5] == 5 [A]? [英] With C arrays, why is it the case that a[5] == 5[a]?

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

问题描述

由于乔尔在堆栈溢出播客#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]

乔尔说,这是因为指针算法,但我还是不明白。 为什么 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] 是这5 元素进一步从 A 的价值,这是同 *(A + 5),并从我们知道这些都是平等的小学数学。 (加法是可交换。)

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.)

这篇关于随着C数组,为什么是这样一个[5] == 5 [A]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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