Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use address of first element of struct, rather than struct itself?

Tags:

c

struct

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?

like image 471
Magnus Avatar asked Nov 04 '13 20:11

Magnus


People also ask

How do I find the address of a struct?

In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.

Can a struct have itself as a member?

A structure T cannot contain itself.

Is the name of a struct a pointer?

Pointers can be used to refer to a struct by its address. This is useful for passing structs to a function. The pointer can be dereferenced using the * operator. The -> operator dereferences the pointer to struct (left operand) and then accesses the value of a member of the struct (right operand).

Is struct variable a pointer?

Like every other data type, structure variables are stored in memory, and we can use pointers to store their addresses. Structure pointer points to the address of the structure variable in the memory block to which it points. This pointer can be used to access and change the value of structure members.


1 Answers

Instead of that:

memcpy(&l.a, &inp->a, sizeof(foo_t)); 

you can do that:

memcpy(&l, inp, sizeof(foo_t)); 

While it can be dangerous and misleading, both statements actually do the same thing here as C guarantees there is no padding before the first structure member.

But the best is just to copy the structure objects using a simple assignment operator:

l = *inp; 

Why would one want to use this style?

My guess: ignorance or bad discipline.

like image 90
ouah Avatar answered Oct 18 '22 10:10

ouah