当访问一个数组时,我们使用运算符[]
,如下所示:
int a[5];
...
a[b] = 12;
上面的变量 b
的正确数据类型是什么?
我发现 a[b]
等同于 *(a + b)
,这让我觉得我想要 b
为 void*
或 size_t
但我不确定。
最佳答案
来自 C 标准(ISO/IEC 9899:TC2) Sec 6.5.2.1 数组下标
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, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer,E1[E2]
designates theE2-th
element ofE1
(counting from zero).
关于c - 运算符 [] 的正确输入数据类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17810995/