8.3.4/8 N3797:
[Example:
consider
int x[3][5]
;Here
x
is a 3 × 5 array of integers. Whenx
appears in an expression, it is converted to a pointer to (the first of three) five-membered arrays of integers. In the expressionx[i]
which is equivalent to*(x+i)
,x
is first converted to a pointer as described; thenx+i
is converted to the type ofx
, which involves multiplyingi
by the length of the object to which the pointer points, namely five integer objects [...]
因为 x
的类型是“由 5 个整数组成的 3 个数组的数组”,我们也有 x+i。假设 i = 2;
x + i
(称他为 arr
)元素在转换为包含 5 个整数的 3 个数组的数组后的值是多少?我的意思是 arr[3]
等于什么?
最佳答案
arr[3]
是一个包含五个整数的数组。原因如下:
When x appears in an expression, it is converted to a pointer to (the first of three) five-membered arrays of integers
这意味着在表达式中使用 arr
将导致类型为 int(*)[5]
(已衰减)。
对于 x[3]
,相当于 *(x+i)
,首先将 x 翻译成 int(*)[5 ]
键入并推进它,然后您取消引用(记住 *)该指针,从而获得 int[5]
类型。
不幸的是,指针指向了一个无效的内存点,因此对这个包含五个整数的数组的任何操作都是未定义的行为/访问冲突。
我同意这篇文章对此确实不清楚,这两个句子几乎像是一个在另一个之前(也有点晦涩)。
我会改写为:
Here x is a 3 × 5 array of integers. When x appears in an expression, it is converted to a pointer to (the first of three) five-membered arrays of integers. In the expression x[i] which is equivalent to *(x+i), x is first converted to a pointer as described; after the pointer increment x+i (which in a byte-wise fashion involves multiplying i by the length of the object to which the pointer points, namely five integer objects), x+1 gets converted to the type pointed by x [...]
关于c++ - 指向数组转换的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956999/