July 5, 2015

imamLL a simple C linked list library

C programming language does not have a linked list implementation like other programming languages such as java. Since C program gives more control to it's users, it is up to users how they implement their own linked list for their programs. imamLL is a linked list implementation library for C designed to be efficient and flexible. Some of the features of imamLL library are
  • Dynamically allocate data at any given point in the program runtime 
  • Add elements of arbitrary sizes into the lists 
  • Navigate through the elements in both forward and backward 
  • Add, remove, modify and get elements from the lists
In this tutorial, we are going to build a simple program using imamLL library.

First, we download imamLL library from the following link:


imamLL-1.3.tar.gz

After extracting the file we run ./build.sh in the terminal to install the library into the system.

Now, we create a blank text file and name it num_list.c

The content of the file is shown below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <imamll.h>        /*header for imamLL */

struct imamLL *num_list = NULL;
struct imamLL_element *element = NULL;

int main (int argc, char** argv)
{
    num_list = imamLL_list_create();
   
    if ( num_list == NULL) {
        printf ("Can not create the list\n");
        exit (EXIT_FAILURE);
    }
   
    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 10;
   
    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 20;

    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 30;
   
    imamLL_list_rewind (num_list);

    while ((element = imamLL_element_get_next(num_list)) != NULL) {
        printf ("%d\n", *((int *)element->data));
    }
   
    imamLL_list_destroy (num_list);

    return 0;
}


Now to compile the num_list.c, in the terminal:

gcc -Wall -o num_list num_list.c -limamll

The program above program can be easily understood by reading the Intro.html file found in the imamLL directory. There are also few more example programs located in the examples directory of imamLL.

No comments:

Post a Comment