Pointers to Structs

We learned how to use struct keyword to create a structure and used it to store the words counts instead of using two arrays.

As any variable in C, the struct type variable is allocated somewhere in memory, so you could get its address:

struct example {
	int a;
	char *s;
};

struct example var = { 1, "test" };
struct example *p = &var;

Given the pointer p which points to struct example, you can access fields a and b as (*p).a and (*p).s. Note the parentheses: without them, *p.a would be understood as *(p.a) which is a syntax error because p is not a struct, so you cannot use . to access its fields.

Pointers to structs are used so often in C that writing (*p). seems too long, and not too readable. So C has a special syntax for accessing fields by the pointer: p->s (the “arrow” is a dash, followed by a “greater than” sign). With this, the example will look like below:

#include <stdio.h>

struct example {
  int a;
  char *s;
};

int main() {
  struct example var = { 42, "test" };
  struct example *p = &var;
  printf("%d : %s\n", var.a, var.s);
  printf("%d : %s\n", (*p).a, (*p).s);
  printf("%d : %s\n", p->a, p->s);
  return 0;
}

Note that all three printf calls print the same result: all these ways of accessing the fields of the struct are equal.

Allocating memory for structs

Similar to how we allocate memory for arrays, we can allocate memory for structs. Consider the same struct example as defined above. We can write:

struct example *p;

p = malloc(sizeof(*p));

This will allocate the exact amount of bytes needed to store this struct, and we will be able to use p->a and p->s to access the fields of the struct. Of course, (*p).a and (*p).s` will work too.

When you are done with your allocated memory, use free(p).

The main reason why we need to be able to allocate memory for structs is for a very special case when a struct holds one or more pointers to another struct(s), building some kind of a nested structure in memory (think about a tree with branches). On the next page we'll make a small detour from the C programming language per se and will talk about very important concepts: linked lists. We'll talk about them soon!

© Alexander Fenster (contact)