Linked Lists and the new Operator

A common way to use pointers with structs is to create a linked list. Start by defining a struct to hold a single list element:

struct link { int val; link* next_link; // pointer to another link struct };

Now you want to be able to keep track of a space in memory without assigning a variable name to it. To do this, use the new operator with a pointer:

link* list = new link; // reserves a space in memory for one link

Now you can assign information to this list element:

list->val = 3;

At this point, the other data member, list->next_link, is not pointing to anything. It should be set to NULL to indicate this. You could have it point to a new link by repeating the same process as above:

list->next_link = new link; list->next_link->val = 5;

Now the linked list contains two links: one with val=3 and the other with val=5. Meanwhile list->next_link->next_link is invalid and should be set to NULL until you use it new to create another link. Thus, a NULL value in the next field indicates the end of the list.

Before a program terminates, you should dispose of dynamically allocated memory. All pointers on which you used the new operator should be released using the corresponding delete operator. The following code segment demonstrates one way to delete a linked list like the one above: