On Mon, 15 Sep 2003 17:20:41 GMT, Joe Wright
typedef struct arr {
int arr[SA];
} arr;
arr st_arr;
C makes arrays difficult. Their expression results in a pointer to its
first element, they cannot be passed by value. Shucks. But what of a
struct consisting of an array? You can do anything with the struct that
you can with the array. What I have not realized until today is, you can
assign the 'value' of a struct (the whole thing) to a local array of the
same size (carefully), as above.
*((arr *)array) = st_arr; /* assign the struct to the local array */
This works (I think) because array in this context is pointer. Casting
it to a struct pointer and dereferencing it creates perfect lvalue
target for the assignment of a struct.
I think technically this is illegal (UB) because you are accessing an
object using a type (lvalue) other than its correct (here, declared)
type or character, or one of the minor variations allowed in 6.5p7; at
least I think that the fifth exception there is intended only to allow
*sub*objects of an aggregate to be accessed by (as part of) an access
to that aggregate, as is clearly necessary, not to allow a subobject
to be accessed *as* the aggregate, but that could be clearer.
Theoretically it could fail because the struct 'st_arr' may contain
padding after the only element arr, while 'array' must not, and struct
assignment may (and usually does) copy padding. In practice I think
the chance of this is about equal to that of winning the lottery while
being hit by a meteorite.
It could also screw up aggressive type-aware optimization, leading to
use of stale cached values, although on current systems I know of
int[10] seems a rather poor candidate for caching.
So, yes it probably does work. But it's much cleaner to just define
your objects of the struct type, arr, in the first place, and assign
or pass or return them; you can still easily use the array member.
- David.Thompson1 at worldnet.att.net