What's the point?

As we move into the second week of class we continued our discussion on pointers. Last post we talked about syntax around pointers and showed using them. We left off wondering how useful pointers were as the seemed redundant to what we could already do with normal variables and address references. Let’s take another look at a pointer but this time with a struct.


struct date {

  int month;

  int day;

  int year;

}

struct date todaysDate;

struct date *datePtr

Here you can see that we have defined a date struct, defined a variable of type date structure and defined a variable of type pointer to date structure. Base on this we can now use those to set datePtr to point to todaysDate.


datePtr = &todaysDate;

At this point datePtr now holds the address of the value of todaysDate. All we need to do to assign a value via the pointer is to use the indirection operator.


(*datePtr).day = 23;

Wait… what’s with the parens around the pointer? Well, the parens are required because the member operator `.` has a higher precedence than the indirection operator `*`. Because pointers to structures are used so often there is an easier way to refer to them. It’s called the structure pointer operator `->`. This allows you to skip the parens and write much cleaner code as follows.


x->y

// is equivalent to 

(*x).y

Now that we know that pointers can be used for structures it leads us to the next use for pointers, members of structures.


struct date {

  int *month;

  int *day;

  int *year;

}

This idea of using structures that contain pointers is where the power of pointers becomes apparent. Using this idea you are able to create well known data structures such as linked lists and trees. Let’s take a look at creating a linked list with structures and pointers. A linked list is a data structure made up of elements (nodes) that are not stored in consecutive blocks of memory. In order to accomplish this each node typically has a value and a pointer to the next node in the list.


// create a struct of our node

struct node {

  int value;

  struct node *next;

}

// create a few nodes

struct node n1, n2, n3;

// assign values to the nodes

n1 = 10;

n2 = 20;

n2 = 30;

// set up the "link" of our list

n1.next = &n2;

n2.next = &n3; 

We now have a linked list and you can use that to trace through the list to find the values using the first node in the list.


int value2;

value2 = n1.next->value

We have now used pointers and structures to create a linked list data structure in C. Next time we will look at more ways to use pointers and learn a little about memory management in C.