Re: Struct compares/copies
- From: "Army1987" <please.ask@xxxxxx>
- Date: Sun, 17 Jun 2007 09:55:46 +0200
<bb@xxxxxxx> ha scritto nel messaggio
news:s618731ejdtvf2rm0p8ipj6ll0dhsdfitr@xxxxxxxxxx
sniipQ: I need to copy and compare C Structs.
Is this the safe and quick way to do it?:
As the comapre (new == old) made the compiler unhappy I didn't want to
Copying is easy: new = old;
trust the assign (old = new).
Well once I've found a change I do have to go through each field to
For safe and meaningful comparison, compare on a field-by-field basis,
comparing the most significant fields first. Typically one would write
a function to do this.
and action the changes. However the changes are rare, so I wanted to
get the 'compare' over and done with asap, hence the 'old == new' as
there can be quite a few fields in the structure (20+ at the mo).
It is not sweet -- the advice is wrong (except in the oddest ofWell I have an odd situation because it has worked for me. Can you (if
situations). It is entirely possible for memcmp to return non-zero
when the two structures are equal in all important respects (i.e. have
identical values in all members).
you have the time and inclination) tell me why memcmp would do this
(is it because of 'structure' padding/alignment and that two
'identical' structs not being identical)? I was concerned (hence the
question in the 1st place).
Even if there is no padding, the structures
struct words {
char word1[8] = { 'H', 'e', 'l', 'l', 'o', '\0', 42, 73 }
char word2[8] = { 'w', 'o', 'r', 'l,' 'd', '\0', 1, 95 }
} a;
and
struct words {
char word1[8] = { 'H', 'e', 'l', 'l', 'o', '\0', 12, 23 }
char word2[8] = { 'w', 'o', 'r', 'l,' 'd', '\0', 47, 79 }
} b;
don't memcmp equal, even if any reasonable person shouldn't
distinguish them in most cases.
.
- Follow-Ups:
- Re: Struct compares/copies
- From: Ben Bacarisse
- Re: Struct compares/copies
- References:
- Struct compares/copies
- From: bb
- Re: Struct compares/copies
- From: Richard Heathfield
- Re: Struct compares/copies
- From: bb
- Struct compares/copies
- Prev by Date: Re: factorial and exponent
- Next by Date: Re: Structure
- Previous by thread: Re: Struct compares/copies
- Next by thread: Re: Struct compares/copies
- Index(es):
Relevant Pages
|