C99 - 特别是第 6.2.6.1 节第 4 段 - 声明允许将对象表示复制到 unsigned char 数组中:
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
一样。