Node:Initializing your data structure, Previous:Designing your data structure, Up:Setting up a data structure
Once you understand your data structure, you can set about initializing it in the following way:
struct town { struct town *north; struct town *south; struct town *east; struct town *west; char name[50]; };
struct town *root, *current;
The root
pointer is used to point to the root node of the
data structure, and the current
pointer points to the node
with which we are currently working.
root = (struct town *) malloc (sizeof (struct town));
Be sure to check for errors. The variable root
will be a null
pointer if no memory could be allocated for the node.
root->north = NULL; root->south = NULL; root->east = NULL; root->west = NULL; strcpy (root->name, "New Haven");
Note that NULL
pointers tell the program when it has come to the
edge of the data structure, that is, when it has found a link that
doesn't lead anywhere. At the moment, the links of the root node do not
point anywhere. This will change as we add more nodes to the data
structure.
current = (struct town *) malloc (sizeof (struct town));
current->north = NULL; current->south = root; current->east = NULL; current->west = NULL; strcpy (current->name, "North Haven");
root->north = current;
See Controlled recursion with data structures, for a practical example of building a simple linked list programmatically.