Re: store contents of structure into an array





n00dle wrote:
> hi,
> see if i want to copy the contents of a char arrary into a equally
> size struct, assuming that the structure has no holes, padding etc., i
> can use
>
> structure = *(t_structure *) array;

There are (at least) two things wrong with this. First,
the assumption of "no padding" is risky in the extreme, and
is an invitation to trouble later on. Second, you've got
potential alignment problems: if the alignment requirement
for the struct is stricter than that provided by the char
array, there's no telling what may happen.

> but if i want to do things the other way round i.e. copy contents of
> the structure to an char array. do i specifically need to have a loop
> to do so, or is there a more elegant way to do it.

Following your first (dangerous) model, you could write

*(t_structure *)array = structure;

.... with all the same drawbacks as the original.

memcpy() moves arbitrarily-aligned chunks of memory
around -- but even so, the "no padding" assumption is a
possible problem. Why do you need to assume it? What
are you trying to do?

--
Eric.Sosman@xxxxxxx

.



Relevant Pages