With arrays, why is it the case that a[5] == 5[a]?

2018-12-30 23:04发布

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 says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?

17条回答
看风景的人
2楼-- · 2018-12-30 23:28

In C arrays, arr[3] and 3[arr] are the same, and their equivalent pointer notations are *(arr + 3) to *(3 + arr). But on the contrary [arr]3 or [3]arr is not correct and will result into syntax error, as (arr + 3)* and (3 + arr)* are not valid expressions. The reason is dereference operator should be placed before the address yielded by the expression, not after the address.

查看更多
荒废的爱情
3楼-- · 2018-12-30 23:29

For pointers in C, we have

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

and also

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

Hence it is true that a[5] == 5[a].

查看更多
刘海飞了
4楼-- · 2018-12-30 23:30

One thing no-one seems to have mentioned about Dinah's problem with sizeof:

You can only add an integer to a pointer, you can't add two pointers together. That way when adding a pointer to an integer, or an integer to a pointer, the compiler always knows which bit has a size that needs to be taken into account.

查看更多
后来的你喜欢了谁
5楼-- · 2018-12-30 23:32

in c compiler

a[i]
i[a]
*(a+i)

are different ways to refer to an element in an array ! (NOT AT ALL WEIRD)

查看更多
泪湿衣
6楼-- · 2018-12-30 23:32

In C

 int a[]={10,20,30,40,50};
 int *p=a;
 printf("%d\n",*p++);//output will be 10
 printf("%d\n",*a++);//will give an error

Pointer is a "variable"

array name is a "mnemonic" or "synonym"

p++; is valid but a++ is invalid

a[2] is equals to 2[a] because the internal operation on both of this is

"Pointer Arithmetic" internally calculated as

*(a+3) equals *(3+a)

查看更多
零度萤火
7楼-- · 2018-12-30 23:34

To answer the question literally. It is not always true that x == x

double zero = 0.0;
double a[] = { 0,0,0,0,0, zero/zero}; // NaN
cout << (a[5] == 5[a] ? "true" : "false") << endl;

prints

false
查看更多
登录 后发表回答