我听到了有关C标准保证结构布局一致性程度的不同说法。认为其程度有限的论点提到了严格的别名规则。例如,比较这两个答案:https://dev59.com/xG865IYBdhLWcg3wivGi#3766251 和 https://dev59.com/xG865IYBdhLWcg3wivGi#3766967。
在下面的代码中,我假设所有结构体
无论强制转换是否会导致错误,它是否违反了严格的别名规则?
在下面的代码中,我假设所有结构体
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
没有报错。
void *
到struct list *
)。 - chux - Reinstate Monicafind_id()
中,@chux ((struct { char *id; } *)(l->ptr.either))->id
。 - nebuch(type) object
,根据C89标准的§3.3.4,这是一个强制类型转换;请参见http://port70.net/~nsz/c/c89/c89-draft.html#3.3.4。 - nebuchid
。将其保留在foo
和bar
开头完全可以正常工作。 - R.. GitHub STOP HELPING ICE