I've just come upon yet another code base at work where developers consistently use the address of the first element of structs when copying/comparing/setting, rather than the struct itself. Here's a simple example.
First there's a struct type:
typedef struct {
int a;
int b;
} foo_t;
Then there's a function that makes a copy of such a struct:
void bar(foo_t *inp)
{
foo_t l;
...
memcpy(&l.a, &inp->a, sizeof(foo_t));
...
}
I wouldn't myself write a call to memcpy
in that way and I started out with suspecting that the original developers simply didn't quite grasp pointers and structs in C. However, now I've seen this in two unrelated code bases, with no common developers so I'm starting to doubt myself.
Why would one want to use this style?
PyObject
; all Python objects start with aPyObject
member, and they're usually passed around withPyObject *
pointers so you don't have to hardcode the actual type of the object you're working with. – user2357112 supports Monicamemcpy
becomes safe if this is the final argument:sizeof(foo_t) - offsetof(foo_t, a)
. – Darren Stonel
. – Guilherme Bernal