在C和C指数[数组]数组访问++ [英] Accessing arrays by index[array] in C and C++
问题描述
因此,有这个小动作问题,有些面试官喜欢问无论出于何种原因:
So, there is this little trick question that some interviewers like to ask for whatever reason:
int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?
从我能理解, A [B]
被转换为 *(A + B)
和自加法是可交换它并没有真正不管他们的顺序,因此 2 [A]
真的是 *(2 + A)
和工作正常。
From what I can understand, a[b]
gets converted to *(a + b)
and since addition is commutative it doesn't really matter their order, so 2[a]
is really *(2 + a)
and that works fine.
这是通过保证C和/或C ++语言的规范工作?
Is this guaranteed to work by C and/or C++'s specs?
推荐答案
是的。 6.5.2.1款(C99标准)描述的参数在 []
运营商:
Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the []
operator:
其中前pressions应该是一个类型的指针对象键入
时,其他前pression应具有整数类型,结果有键入键入
。
One of the expressions shall have type "pointer to object
type
", the other expression shall have integer type, and the result has type "type
".
6.5.2.1条第2款(强调):
6.5.2.1 paragraph 2 (emphasis added):
一个后连接点¯x前pression随后在方括号中前pression []
是一个下标
阵列对象的元素的指定。 下标运算符的定义 []
是 E1 [E2]
与(*((E1)+(E2)))
。由于转换规则的那
适用于二进制 +
运营商,如果 E1
是一个数组对象(等同于一个指针
数组对象的初始元素)和 E2
是一个整数, E1 [E2]
指定的 E2
-th
E1
(从零算起)。元素
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
报告说,没有什么要求的参数以 []
是明智的。
It says nothing requiring the order of the arguments to []
to be sane.
这篇关于在C和C指数[数组]数组访问++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!