Is listing from TYPE * to unsigned char *?

C99 - in particular, section 6.2.6.1, clause 4 - indicates that copying the representation of an object into an unsigned array of char is allowed:

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. 

My question is: can we avoid unnecessary memory allocation and copy operations with simple casting? For example:

 struct { int foo; double bar; } baz; unsigned char *bytes = (void *)&baz; // Do stuff with the baz structure. // Do things with the bytes array. 

Of course, the size will need to be tracked, but is it legal first of all, or does it fall into the scope of the implementation defined by the implementation or undefined?

I ask because I implement an algorithm similar to qsort , and I would like it to work for any array, regardless of type, as qsort does.

+7
c void-pointers opaque-pointers
source share
1 answer

6.5 Expressions

[...]
6 The valid type of an object to access its stored value is the declared type of the object, if any .87) If the value is stored in an object that does not have a declared type, through an lvalue having a type that is not a character type, then the lvalue type becomes an effective type object for this access and for subsequent accesses that do not change the stored value. If the value is copied to an object that does not have a declared type using memcpy or memmove, or copied as an array of symbol type, then the effective type of the changed object for this access and for subsequent accesses that do not change value is the effective type of the object from which the value is copied if it is. For all other calls to an object that does not have a declared type, the effective type of the object is simply the lvalue type used for access.
7 The object must have a stored value, access to which can only be obtained using the lvalue expression, which has one of the following types: 88)

  • a type compatible with an efficient object type,
  • qualified version of the type compatible with the effective type of the object,
  • a type that is a signed or unsigned type corresponding to an effective type of Object,
  • a type that is a signed or unsigned type corresponding to a qualified version; an effective object type,
  • a type of aggregate or association that includes one of the above types among its members (including, recursively, a member of a joint or joint union) or
  • character type .

The emphasis is mine. Thus, you can consider any type as an array of characters ( unsigned char[] , char[] or signed char[] ).

I also quoted paragraph 6 because it makes the opposite not applicable.

+6
source share

All Articles