【发布时间】:2018-12-05 12:33:42
【问题描述】:
基于这个问题 (strange output issue in c) 有一个关于这一行的答案 (provided by @Lundin):
int *ptr = (int*)(&a+1);
他说的地方:
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) );
}
我想知道是不是这样:
int *ptr = *( ( &a ) + 1 );
标准是否明确定义?
编辑:
在某些时候@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 pointer is not correctly aligned68) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.
但我不确定我是否理解正确。
【问题讨论】:
-
@EugeneSh。它在 print 语句中向后移动 1,将其返回到数组的末尾,这应该是有效的。
-
( &a ) + 1- 指向数组。然后取消引用并分配给ptr。 -
@EugeneSh。
&a的类型为int (*a)[5],因此*((&a) + 1)的类型为int *,并指向数组末尾之后的地址。 -
@user3386109
(&a) + 1的类型为(*a)[5]并指向数组。*((&a) + 1)正在取消引用它。 -
@Michi 使指针“过去”一个对象的地址不是问题。指针数学定义明确。如何使用该指针是一个问题,特别是如果它被取消引用,就像这里一样。
标签: c arrays pointers language-lawyer pointer-arithmetic