这是否违反了严格的别名规则?

Does this break the strict aliasing rule?

受我最近对 ​​post: 评论的启发,我想知道以下代码是否违反了严格的别名规则:

#include <stdio.h>

int main(void)
{
    int num[3] = { 1, 2, 3 };

    printf("num[1] = %d\n", *(int *)((char *)num + sizeof(int)));

    return 0;
}

我知道取消引用类型转换为 char 以外的其他类型的指针是违规的,但在这里,原始指针的类型为 int *。它在转换为 char * 然后转换为 int *.

后被取消引用

这是否违反了严格的别名规则?

不会破坏严格的别名。

在将 num 转换为 char * 并对其执行算术运算后,生成的指针将转换为 int *,并且该指针指向有效的 int目的。所以它可以安全地取消引用。

引用 C11,章节 §6.5p7

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

  1. a type compatible with the effective type of the object

还有

引用 C11,章节 §6.5p6

The effective type of an object for an access to its stored value is the declared type of the object, if any....

强调我的

这里 num 指向的对象的有效类型确实是 int 因此可以用指向 int.

的指针取消引用它