1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Advanced Pointers

By David Bolton, About.com

3 of 8

Explanation of Example 1 Continued

The function AddElement does all the real work. It uses malloc() to allocate memory for
  • The new node
  • The new element
  • The key string within the element.
It's very good practice to always check calls to malloc() in case the application runs out of memory, This complicates AddElement a bit because if any of the mallocs() fail, it backs out and frees up any memory that has been allocated. If it can't allocate the memory for the element's key, it frees up the element.

Note that after freeing a pointer I set it to 0. That's also a very good habit to get into. If the element can't be created then the node itself is freed up. AddElement is very much like a constructor in C++. It either fully succeeds in allocating everything or it fails and leaves allocated memory in a consistent state. The code relies on every node having a valid dataElement. You don't have to do this but I reckon it keeps the functions that use the list a bit simpler- there's no need to check if data is valid.

Only if the node etc is successfully allocated is the node added on the end of the list. In the test code (in the main function), every node added is checked to see that it worked ok. If any fail, no more are added as the only reason it could fail is running out of memory.

As each node is added, its associated element gets the auto incremented id and a string key.

The function getNextID() uses a static variable to make auto incrementing work. This starts with the initial value of 0 but because it is marked static, the value is not lost when the function exits. The first time it is called it returns 0 and then increments to 1. Next time it returns 1 and increments to 2.

int getNextID() {
  static int id=0;
  return id++;
}

On the next page : More About Example 1

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Explanation of Example 1 Continued

©2009 About.com, a part of The New York Times Company.

All rights reserved.