Kenny Woo

finding new ways to procrastinate.

github twitter linkedin email rss
Dereferencing Pointers within Struct Pointers in C
Jan 15, 2014
2 minutes read

I recently found myself having to review this topic so I thought I’d write about it as a personal exercise. Hopefully this will serve as a useful reference for you as well.

Let’s start with a struct that is a food_container that carries fruits and veggies in separate containers (which are also structs).

typedef struct {
    int celery;
} vegetable_container;

typedef struct {
    int mangoes;
} fruit_container;

typedef struct {
    vegetable_container veggies;
    fruit_container *fruits;
} food_container;

First, we create a pointer to a food_container and allocate memory for it:

food_container *food_stash = malloc(sizeof(food_container));

This allocates memory for the structure pointed to by food_stash. Note that food_container contains a pointer to a fruit_container. This malloc will only allocate memory for the pointer, not for the actual structure that the pointer points to. Therefore, our next step is to allocate memory for that structure:

food_stash->fruits = malloc (sizeof(fruit_container));

Now we want to populate the data starting with the vegetable_container:

(*food_stash).veggies.celery = 10;
food_stash->veggies.celery = 10;

Both lines above are equivalent. The second notation uses a structure dereferencing operator that dereferences the structure as well as accesses the specified member within the structure. Let’s take a look at the how to populate data in the fruit_container:

(*(*food_stash).fruits).mangoes = 4;
food_stash->fruits->mangoes = 4;

Again, both statements are equivalent. Since fruits is a pointer to fruit_container, we must first dereference it before we can access its members.

Finally, once we’re done manipulating these structures, we must free the allocated memory. Order matters here as if you free the wrong one first, you no longer have access to the inner structures.

free(food_stash->fruits);
free(food_stash);

As a side note, the following preprocessor directives are needed:

#include <stdio.h>
#include <stdlib.h>     // malloc()

And that’s it! Try practicing this from scratch with various data types to get the hang of it.


Back to posts