Dereferencing a Pointer to a struct

suggest change

Let’s say we have the following structure:

struct MY_STRUCT 
{
    int my_int;
    float my_float;
};

We can define MY_STRUCT to omit the struct keyword so we don’t have to type struct MY_STRUCT each time we use it. This, however, is optional.

typedef struct MY_STRUCT MY_STRUCT;

If we then have a pointer to an instance of this struct

MY_STRUCT *instance;

If this declaration appears at file scope, instance is initialized with a null pointer when the program starts. If it appears inside a function, the pointer is indeterminate until it is initialized. It must point to a valid MY_STRUCT object, or to allocated storage of that type, before it is dereferenced. For example:

MY_STRUCT info = { 1, 3.141593F };
MY_STRUCT *instance = &info;

When the pointer is valid, we can dereference it to access its members using one of two different notations:

int a = (*instance).my_int;
float b = instance->my_float;

While both these methods work, it is better practice to use the arrow -> operator rather than the combination of parentheses, the dereference \* operator and the dot . operator because it is easier to read and understand, especially with nested uses.

Another important difference is shown below:

MY_STRUCT copy = *instance;
copy.my_int    = 2;

In this case, copy contains a copy of the struct that instance points to. Changing copy.my_int does not change the original struct.

MY_STRUCT *ref = instance;
ref->my_int    = 2;

In this case, ref is another pointer to the same struct. Changing ref->my_int changes that struct.

It is common to pass a pointer to a struct instead of passing the struct by value. Passing a large struct by value copies it. A pointer does not copy the struct, but the function can modify the caller's object unless the pointer is const-qualified.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents