Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers vs direct member access for structs

Say I have a struct like the following ...

typedef struct {
  int WheelCount;
  double MaxSpeed;
} Vehicle;

... and I have a global variable of this type (I'm well aware of the pitfalls of globals, this is for an embedded system, which I didn't design, and for which they're an unfortunate but necessary evil.) Is it faster to access the members of the struct directly or through a pointer ? ie

double LocalSpeed = MyGlobal.MaxSpeed;

or

double LocalSpeed = pMyGlobal->MaxSpeed;

One of my tasks is to simplify and fix a recently inherited embedded system.

like image 861
Alex Marshall Avatar asked Aug 25 '09 15:08

Alex Marshall


People also ask

Should I use a pointer to a struct?

Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.

Why do we use pointers for structs in C?

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.

How do struct members connect to pointers?

To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.

Can you have a pointer to a struct in C?

Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures. Structure in C is a user-defined data type which is used to store heterogeneous data in a contiguous manner.


1 Answers

In general, I'd say go with the first option:

double LocalSpeed = MyGlobal.MaxSpeed;

This has one less dereference (you're not finding the pointer, then dereferencing it to get to it's location). It's also simpler and easier to read and maintain, since you don't need to create the pointer variable in addition to the struct.

That being said, I don't think any performance difference you'd see would be noticable, even on an embedded system. Both will be very, very fast access times.

like image 187
Reed Copsey Avatar answered Oct 13 '22 11:10

Reed Copsey