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一样.
解决方法
6.5 Expressions
[…]
6 The effective type of an object for an access to its stored value is the declared type of the
object,if any.87) If a value is stored into an object having no declared type through an
lvalue having a type that is not a character type,then the type of the lvalue becomes the
effective type of the object for that access and for subsequent accesses that do not modify
the stored value. If a value is copied into an object having no declared type using
memcpy or memmove,or is copied as an array of character type,then the effective type
of the modified object for that access and for subsequent accesses that do not modify the
value is the effective type of the object from which the value is copied,if it has one. For
all other accesses to an object having no declared type,the effective type of the object is
simply the type of the lvalue used for the access.
7 An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:88)
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the
object,- a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,- an aggregate or union type that includes one of the aforementioned types among its
members (including,recursively,a member of a subaggregate or contained union),or- a character type.
强调我的.因此,您可以将任何类型视为字符数组(unsigned char [],char []或signed char []).
我还引用了第6段,因为它反过来不适用.