LinkedList implementation

This is a discussion on LinkedList implementation within the C Programming forums, part of the General Programming Boards category; I'm preparing for interviews and I want to get comfortable with C after years of development in Java and C#. ...

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    5

    LinkedList implementation

    I'm preparing for interviews and I want to get comfortable with C after years of development in Java and C#. I decided to start with the implementation of basic data structures and this brings me to the LinkedList.

    Program is:

    Code:
    struct Node {
        struct Node* next;
        int data;
    };
    
    struct LinkedList {
        struct Node* head;
        struct Node* tail;
    };
    Code:
    int main(int argc, char** argv) {
    
        struct LinkedList *list = NULL;
        printf("Declared the list");
        LLInitialize(list);
        printf("Initialized the list");
    }

    Code:
    void LLInitialize(struct LinkedList *list) {
    
        list = (struct LinkedList*)malloc(sizeof(struct LinkedList));
        list->head = NULL;
        list->tail = NULL;
    }

    After the call to the LLInitialize() in the debugger I do not see the head/tail fields being NULL. They just are not there as if the malloc was never called. Why is that?
    Last edited by rire1979; 12-19-2009 at 01:41 PM. Reason: Clarification

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    That's because the list parameter you're using to save the return value of malloc, is a local variable. The list variable you have declared outside the LLInitialize will still point to NULL even after you've called LLInitialize. If you want to make the changes appear outside LLInitialize (and thus avoid a memory leak), the parameter should be a struct LinkedList **list instead (you also need to edit the function to reflect that).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Java Linked List implementation equivalent in C?
    By pbtrn10k in forum C Programming
    Replies: 8
    Last Post: 08-19-2009, 11:48 AM
  2. rand() implementation
    By habert79 in forum C Programming
    Replies: 4
    Last Post: 02-07-2009, 01:18 PM
  3. Something about a linkedlist program..
    By ozumsafa in forum C Programming
    Replies: 8
    Last Post: 10-17-2007, 02:14 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 01:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21