I just use memcpy() and don't think about that (yes, syntax can get real ugly, but it is "more natural" operation for me)... But, do you perhaps know what standard (ANSI) says about that?
Printable View
Yes, but what I suggested is not really to solve the copying problem, but rather the underlying problems caused by gaps/padding in a struct when using it across applications - and as my edit says, that's what I expect you are doing if you are using CRC to check it's consistency. Within an application, struct contents should only get lost if the application itself is buggy.
--
Mats
Oh, and another point is of course that copying with memcpy() gives you no typechecking:
--Code:struct X
{
int a;
};
struct Y
{
int b[1000];
};
...
struct X x;
struct Y y;
..
memcpy(x, y, sizeof(y));
// Probably won't get much further, as you've just overwritten 3996 bytes of memory with contents of y.
Mats
But isn't it "weird" that you can do:
but you can't do:Code:struct _s
{
int a;
int b;
} x,y;
x = y;
EDIT: I could be seriously wrong here, but it seems to me that for comparing, you have to use memcmp() (or compare each member individualy). And if you use memcmp(), why not memcpy() too?Code:if (x != y)
{
...
}
Comparing a struct is more complex than that - in C++ you could make a compare operators (operator=, operator<, etc), but except for equality of trivial structs [no indirect content], you can't really compare structs directly. For example:
Is a == b?Code:struct A
{
int x;
char *str;
};
struct A a, b;
a.x = 7;
a.str = malloc(10);
strcpy(a.str, "Hi");
b.x = 7;
b.str = malloc(10);
strcpy(b.str, "Hi");
Also, at least memcmp() won't overwrite some other memory in the process, so you have saved yourself one potential bug.
--
Mats
But when you have pointers in struct, it's risky/invalid to use "a=b;" too (and memcpy() of course), so i personaly don't see any benefit in assigning struct to struct (furthermore, it seems to me risky and implemented as some sort of "hack"). But anyway, thanks matsp for yet another "lessons" ;)