我听说过关于 C 标准在多大程度上保证结构布局一致性的相互矛盾的事情。有限范围的争论提到了严格的别名规则。例如,比较这两个答案:https ://stackoverflow.com/a/3766251/1306666和https://stackoverflow.com/a/3766967/1306666。
在下面的代码中,我假设所有结构foo
,bar
和struct { char *id; }
都char *id
在同一个位置,如果它是唯一访问的成员,则可以安全地在它们之间进行转换。
不管转换是否会导致错误,它是否违反了严格的别名规则?
#include <string.h>
struct foo {
char *id;
int a;
};
struct bar {
char *id;
int x, y, z;
};
struct list {
struct list *next;
union {
struct foo *foop;
struct bar *barp;
void *either;
} ptr;
};
struct list *find_id(struct list *l, char *key)
{
while (l != NULL) {
/* cast to anonymous struct and dereferenced */
if (!strcmp(((struct { char *id; } *)(l->ptr.either))->id, key))
return l;
l = l->next;
}
return NULL;
}
gcc -o /dev/null -Wstrict-aliasing test.c
注意gcc
没有错误。