C数组算术和指针[重复]

时间:2022-09-30 21:17:44

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

可能重复:在C数组中为什么这是真的? a [5] == 5 [a]

I am reading through a tutorial on C and I came across this syntax:

我正在阅读关于C的教程,我遇到了这种语法:

int doses[] = {1, 3, 2, 1000};
doses[3] == *(doses + 3) == *(3 + doses) == 3[doses]

Now the point is to get the int 1000, but the last one doesn't make any sense. Either its late and my brain is not functioning, its something specific to C, or its a typo. I want to cover all my basics when it comes to pointers so reading through it carefully. That means understanding it all. Any answers would be much appreciated!

现在重点是获得int 1000,但最后一个没有任何意义。要么它的晚期和我的大脑没有运作,它的特定于C的东西,或它的错字。我想在指针上涵盖我的所有基础知识,仔细阅读它。这意味着要理解这一切。任何答案将不胜感激!

3 个解决方案

#1


7  

From Wikipedia

Since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a], although this form is rarely used.

由于表达式a [i]在语义上等效于*(a + i),其又等于*(i + a),因此表达式也可以写为i [a],尽管很少使用这种形式。

#2


2  

Yes, array subscripting is commutative in C. e1[e2] is indeed the same as *((e1)+(e2)). But it is useless in production code, and the only purpose of this notation is to make obfuscated source code.

是的,数组下标在C中是可交换的.e1 [e2]确实与*((e1)+(e2)相同。但它在生产代码中是无用的,这种表示法的唯一目的是制作混淆的源代码。

#3


0  

ISO c99 : 6.5.2.1 Array subscripting

1
One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.

1其中一个表达式应具有类型''指向对象类型的指针'',另一个表达式应具有整数类型,结果具有类型''type''。

E1[E2] either E1 will be pointer to object type and E2 will be integer type.

Or,

E1 is integer type and E2 is of pointer to that type

as + is commutative so E1[E2] == E2[E1] , because it's actually evaluated as (*(E1+E2))

因为+是交换所以E1 [E2] == E2 [E1],因为它实际上被评估为(*(E1 + E2))

#1


7  

From Wikipedia

Since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a], although this form is rarely used.

由于表达式a [i]在语义上等效于*(a + i),其又等于*(i + a),因此表达式也可以写为i [a],尽管很少使用这种形式。

#2


2  

Yes, array subscripting is commutative in C. e1[e2] is indeed the same as *((e1)+(e2)). But it is useless in production code, and the only purpose of this notation is to make obfuscated source code.

是的,数组下标在C中是可交换的.e1 [e2]确实与*((e1)+(e2)相同。但它在生产代码中是无用的,这种表示法的唯一目的是制作混淆的源代码。

#3


0  

ISO c99 : 6.5.2.1 Array subscripting

1
One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.

1其中一个表达式应具有类型''指向对象类型的指针'',另一个表达式应具有整数类型,结果具有类型''type''。

E1[E2] either E1 will be pointer to object type and E2 will be integer type.

Or,

E1 is integer type and E2 is of pointer to that type

as + is commutative so E1[E2] == E2[E1] , because it's actually evaluated as (*(E1+E2))

因为+是交换所以E1 [E2] == E2 [E1],因为它实际上被评估为(*(E1 + E2))