Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: Structure packing & padding: what sizeof reports? Any caveats? |
| Date | 2016-08-08 11:29 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <877fbrlfj1.fsf@bsb.me.uk> (permalink) |
| References | <inbgqb9dm89a0el2m4sh8ntqb8541r7miu@4ax.com> <no9dlh$afe$1@dont-email.me> |
Richard Heathfield <rjh@cpax.org.uk> writes:
> On 08/08/16 08:15, Test wrote:
>> I am saving structures and variables to a string. For example:
>> ..
>> struct MixedData
>> {
>> char Data1;
>> int num1;
>> short num2;
>> };
<snip>
>> char mystr[256];
>> struct MixedData whatever;
<snip>
>> memcpy(&mystr[4],&whatever,sizeof(struct MixedData));
<snip>
>> memcpy(&whatever,&mystr[4],sizeof(struct MixedData));
To the OP: I find
memcpy(dest, &whatever, sizeof whatever);
to be more obviously correct. There is no need to check that the type
used in the sizeof is that of declared object 'whatever'. It's a case
of directly writing what you mean rather than something that works.
>> Is above OK
>
> It's horrible, and it isn't guaranteed to work. Your hard-coded 4 is
> one of your problems, since it assumes that there are exactly three
> padding bytes after the Data1 member.
I don't think it does. &mystr[4] is simply where Test wants to put the
data. Yes, the 4 is still a hard-coded number, and that might be a
problem for other reasons, but I don't think it's got anything to do
with padding assumptions.
<snip>
--
Ben.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Structure packing & padding: what sizeof reports? Any caveats? Test <test@.nil.invalid.com> - 2016-08-08 10:15 +0300
Re: Structure packing & padding: what sizeof reports? Any caveats? Ian Collins <ian-news@hotmail.com> - 2016-08-08 19:36 +1200
Re: Structure packing & padding: what sizeof reports? Any caveats? Richard Heathfield <rjh@cpax.org.uk> - 2016-08-08 08:52 +0100
Re: Structure packing & padding: what sizeof reports? Any caveats? Richard Heathfield <rjh@cpax.org.uk> - 2016-08-08 08:51 +0100
Re: Structure packing & padding: what sizeof reports? Any caveats? Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-08-08 11:29 +0100
Re: Structure packing & padding: what sizeof reports? Any caveats? Keith Thompson <kst-u@mib.org> - 2016-08-08 08:56 -0700
Re: Structure packing & padding: what sizeof reports? Any caveats? Barry Schwarz <schwarzb@dqel.com> - 2016-08-08 01:37 -0700
Re: Structure packing & padding: what sizeof reports? Any caveats? James Kuyper <jameskuyper@verizon.net> - 2016-08-08 11:17 -0400
csiph-web