Node:Initializing your data structure, Previous:Designing your data structure, Up:Setting up a data structure
Initializing your data structure
Once you understand your data structure, you can set about initializing it in the following way:
- Declare your structure type. For example:
struct town { struct town *north; struct town *south; struct town *east; struct town *west; char name[50]; };
- Declare two pointers to this type:
struct town *root, *current;
The
root
pointer is used to point to the root node of the data structure, and thecurrent
pointer points to the node with which we are currently working. - Allocate memory for the root node:
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. - Initialize the members of the root 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. - Create a new, non-root node:
current = (struct town *) malloc (sizeof (struct town));
- Initialize the current node:
current->north = NULL; current->south = root; current->east = NULL; current->west = NULL; strcpy (current->name, "North Haven");
- Link neighboring nodes to the current node, as appropriate:
root->north = current;
- Repeat steps 5 through 7, as necessary.
See Controlled recursion with data structures, for a practical example of building a simple linked list programmatically.