Linked Lists

So far we have defined what the variable type node is, and even declared a pointer to a node, but there aren't actually any nodes in existence yet. We rectify that as follows-na:

    linkedlist = calloc(sizeof(node),1);
    linkedlist->numdata = 5;
    linkedlist->nextnode = NULL;

The calloc function (which is in the stdlib library) sets aside space in memory and then blanks it all to zero. It takes two arguments. The first is the size of the item which we want to store, and the second is the number of items. The word sizeof is an internal C word which returns the size of any type which we feed into it. Clearly we are using calloc to set aside a single portion of memory whose size is big enough to store a node. The function calloc then returns a pointer to this allocated memory, and since linkedlist is defined to be a pointer to a node, we can just set it equal to this return value.

The next two lines initialize the values of the two pieces of information inside our new node. We set the int variable equal to the value 5 and we set the pointer to point nowhere for now, by setting it equal to NULL.

There is a second way of achieving the above. The method we used for creating a node, dynamically allocates the memory needed whilst the actual program is running. However, it is also possible to allocate space for a node statically (i.e. we put the details into the program in advance, before it is run). This is done as follows-na:

    node mynode = {5, NULL};

This creates a node called mynode and sets the data inside the node to exactly the same values as in the above. We can still change this data if we want. For example:

    mynode.numdata = 7;
    mynode.nextnode = &mynode;

Here we have set the integer to 7 and made the node point to itself.

Notice the use of the dot instead of the arrow as in the earlier example. This is because of the fact that linkedlist was a pointer to a node, whilst mynode actually is a node. The arrow tells C to follow the pointer first, then assign values, whilst the dot simply assigns the values straight away.

This slightly confusing difference is an essential feature of C. When things are defined statically, one can simply refer to each individual object by name, so no need for pointers. However, if space for objects is allocated dynamically when the program is running, it is not possible to have a separate name for each object, or the same name may be used to refer to different objects at different times during the program's execution. That is where pointers come in handy and explains why one uses arrows-na for assigning values to objects that are being pointed to and dots for objects that are referred to individually by name.