c++ - 指向数组转换的指针

标签 c++ arrays pointers

8.3.4/8 N3797:

[Example:

consider int x[3][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; then x+i is converted to the type of x, which involves multiplying i 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/

相关文章:

c++ - Eclipse- C/C++ <终止,退出值 : -1073741515>

c++ - 通过按空格键结束键盘输入数据,而不是输入键 c/c++

arrays - 在 Windows 批处理文件中,如何回显或索引数组中的第 (n+1) 个元素?

c++ - 没有默认构造函数的对象数组初始化

c - 修改和打印字符串不会产生预期的输出

c++ - 使用 SDL2/C++ 在屏幕上留下痕迹

c++ - OpenACC 当前子句更新数据

php - 如何在 php 数组中插入多个 html 输入字段数据?

c++ - rend指向哪里?

c - cast 指针在这段代码中做了什么?