C99 -- 特别是第6.2.6.1节第4段 -- 规定将对象表示复制到无符号字符数组中是允许的:
当然,需要跟踪大小,但这首先是否合法,或者它属于实现定义或未定义的行为范畴?
我提出这个问题是因为我正在实现类似
struct {
int foo;
double bar;
} baz;
unsigned char bytes[sizeof baz];
// Do things with the baz structure.
memcpy(bytes, &baz, sizeof bytes);
// Do things with the bytes array.
我的问题是:我们是否可以通过简单的强制类型转换来避免额外的内存分配和拷贝操作?例如:
struct {
int foo;
double bar;
} baz;
unsigned char *bytes = (void *)&baz;
// Do stuff with the baz structure.
// Do things with the bytes array.
当然,需要跟踪大小,但这首先是否合法,或者它属于实现定义或未定义的行为范畴?
我提出这个问题是因为我正在实现类似
qsort
的算法,并且希望它适用于任何类型的数组,就像qsort
一样。
char
别名一切,所以这应该没问题。 - EOFchar
没有影响。 - EOFstruct
是与声明类型兼容的类型时,才能成立。 - Deduplicator