相关疑难解决方法(0)

指针到数组重叠的数组末尾

这段代码是否正确?

int arr[2];

int (*ptr)[2] = (int (*)[2]) &arr[1];

ptr[0][0] = 0;
Run Code Online (Sandbox Code Playgroud)

ptr[0][1]访问越界越明显无效arr.

注意:毫无疑问,ptr[0][0]指定相同的内存位置arr[1]; 问题是我们是否被允许通过访问该内存位置ptr.下面是一些表达式确定指定相同内存位置但不允许以这种方式访问​​内存位置的示例.

注2:还要考虑**ptr = 0;.正如马克·凡·莱恩指出,ptr[0]就相当于*(ptr + 0),但是ptr + 0似乎陷入指针运算部的犯规.但通过使用*ptr,可以避免这种情况.

c c++ arrays language-lawyer

21
推荐指数
1
解决办法
1148
查看次数

是"int*ptr =*((&a)+ 1);" 其中"a"是标准明确定义的int [5]?

基于这个问题(c中的奇怪输出问题)有一个答案(由@Lundin提供)关于这一行:

int *ptr = (int*)(&a+1);
Run Code Online (Sandbox Code Playgroud)

在哪里他说:

the cast (int*) was hiding this bug.

所以我带来了以下内容:

#include <stdio.h>

int main( void ){
    int a[5] = {1,2,3,4,5};

    int *ptr = *( ( &a ) + 1 );
    printf("%d", *(ptr-1) );
}
Run Code Online (Sandbox Code Playgroud)

我想知道这是否:

int *ptr = *( ( &a ) + 1 );
Run Code Online (Sandbox Code Playgroud)

标准明确定义了吗?

编辑:

在某些时候@chux指出§6.3.2.3.7哪个是:

A pointer to an object type may be converted to a pointer to a different object type. If the
resulting …
Run Code Online (Sandbox Code Playgroud)

c arrays pointers pointer-arithmetic language-lawyer

10
推荐指数
1
解决办法
243
查看次数

标签 统计

arrays ×2

c ×2

language-lawyer ×2

c++ ×1

pointer-arithmetic ×1

pointers ×1