我以为我真的理解这一点,并重新阅读标准(ISO 9899:1990)只是证实了我明显错误的理解,所以现在我问这里.
以下程序崩溃:
#include <stdio.h>
#include <stddef.h>
typedef struct {
int array[3];
} type1_t;
typedef struct {
int *ptr;
} type2_t;
type1_t my_test = { {1, 2, 3} };
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
type1_t *type1_p = &my_test;
type2_t *type2_p = (type2_t *) &my_test;
printf("offsetof(type1_t, array) = %lu\n", offsetof(type1_t, array)); // 0
printf("my_test.array[0] = %d\n", my_test.array[0]);
printf("type1_p->array[0] = %d\n", type1_p->array[0]);
printf("type2_p->ptr[0] = %d\n", type2_p->ptr[0]); // this line crashes
return 0;
}
Run Code Online (Sandbox Code Playgroud)
比较表达式my_test.array[0]并type2_p->ptr[0]根据我对标准的解释:
6.3.2.1数组下标 …
从我的演讲幻灯片中,它指出:
如下面的代码所示,可以将数组名称分配
给适当的指针,而无需前面的&运算符.
int x;
int a[3] = {0,1,2};
int *pa = a;
x = *pa;
x = *(pa + 1);
x = *(pa + 2);
a += 2; /* invalid */
Run Code Online (Sandbox Code Playgroud)
为什么a += 2;无效?
谁能帮忙澄清一下?
如果你想到一个更好的标题,也可以自由编辑标题.