July 11, 2015

imamLL linked list library store struct elements

As imamLL (imamLL-1.3.tar.gz) is very versatile in storing any type of data into a list, you can store an struct as an element like shown in the following code example:

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

#include "imamll.h"

struct Person {
    char name[24];
    double age;
    double weight;
    double height;
};

struct imamLL *People_list = NULL;          /* Pointer to hold list */
struct imamLL_element *person = NULL;       /* Pointer to hold individual element */
unsigned long c;

int main (int argc, char* argv[])
{
    printf ("Allocating memory for list\n");
   
    People_list = imamLL_list_create();

    if (People_list == NULL) {
        printf ("Can not create the list\n");
        exit (1);
    }
   
    if ((person = imamLL_element_add (People_list, sizeof(struct Person), AT_END)) == NULL) {
        printf ("Can not add element");
        printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
        exit (1);
    }
    strcpy (((struct Person *)person->data)->name, "Md Imam Hossain");
    ((struct Person *)person->data)->age = 27.0;
    ((struct Person *)person->data)->height = 180.0;
    ((struct Person *)person->data)->weight = 67.0;

    printf ("Allocated: %lu Bytes\n", People_list->size);
   
    if ((person = imamLL_element_add (People_list, sizeof(struct Person), AT_END)) == NULL) {
        printf ("Can not add element");
        printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
        exit (1);
    }
    strcpy (((struct Person *)person->data)->name, "Md Salim Hossain");
    ((struct Person *)person->data)->age = 22.0;
    ((struct Person *)person->data)->height = 182.0;
    ((struct Person *)person->data)->weight = 75.0;

    printf ("Allocated: %lu Bytes\n", People_list->size);
   
    while (1) {
        person = imamLL_element_get_next (People_list);
        if (person == NULL) break;
        printf ("*Person*\n");
        printf ("Name: %s\n", ((struct Person *)person->data)->name);
        printf ("Age: %lf\n", ((struct Person *)person->data)->age);
        printf ("Height: %lf\n", ((struct Person *)person->data)->height);
        printf ("Weight: %lf\n", ((struct Person *)person->data)->weight);
    }
   
    printf ("Freed: %d elements\n", imamLL_list_free (People_list));
    printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
   
    return (EXIT_SUCCESS);
}


No comments:

Post a Comment