Cor*_*ion 1 c arrays pointers strict-aliasing
struct test
{
char member1;
char member2;
};
int main(void)
{
struct test structure[] = {'h', 'i'};
static void* p = &structure;
printf("%i", *((int*)p));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们都知道structure应该指向struct中第一个元素的地址.为什么通过这样取消引用它,它会返回地址本身呢?
您的代码表现出未定义的行为.
您正在转换structure *为键入int *和解除引用.当(大部分)大小int更大时,您正在访问离线内存.(这是一个原因,还有一些原因)
+---+---+---+---+
| h | i | ? | ? |
+---+---+---+---+
Print as int: ? ? i h if machine is little endian
In ascii coding
+---+---+---+---+
| 68| 69| ? | ? |
+---+---+---+---+
Print as int: ?? ?? 69 68
Run Code Online (Sandbox Code Playgroud)
结构的正确使用是:
struct test s1 = {'h', 'i'};
struct test s2[] = { {'t', 'o'}, {'d', 'o'} };
printf("s1 : %c, %c\n", s1.member1, s1.member2);
printf("s2[0]: %c, %c\n", s2[0].member1, s2[0].member2);
printf("s2[1]: %c, %c\n", s2[1].member1, s2[1].member2);
Run Code Online (Sandbox Code Playgroud)