Search code examples
carrayslistprogramming-languagespython-3.x

How do we implement the functions of list (which was in python) as arrays in C language?


I need to implement the "list" data-structure that we use in python. list in python : http://docs.python.org/tutorial/datastructures.html I have to implement the functions of list, considering the lists as arrays and need to allocate the memory to it dynamically. I need to use functions, pointers and structures wherever necessary. (In C language!)


Solution

  • To simulate linked list you must study these topics

    1.Dynamic Memory allocation using malloc calloc realloc and free

    2.Structures in c

    3.Basic pointers in c For Dynamic Memory allocation you could visit

    Dynamic Memory Allocation in c

    A nice tutorial is given here Linked List in C

    EDIT

    The array implementation of a list is easier as compared to linked list implementaion.In array implementaion also you could use malloc to dynamically allocate memory for your array and realloc to increase/decrease the memory.

    for e.g

    int *base;
    int initial_size; //Take Input from user.
    base=(int *)malloc(sizeof(int) * initla_size);
    if(!base)  //Ensure if memory is allocated
    {
           //Rest of the code 
    }
    Now to insert eleements you could simply use 
    base[i]=element;
    

    But before this you must study how arrays and pointers work in C language, and more specifically Dynamic memeory allocation part..