0

I am trying to create a singly linked list. I have created five nodes and initialized them with a integer value. But when I print the Linked List I get nothing.

typedef struct node {
    int value;
    struct node* nextPtr;
 } node;

 node *nodePtr;
 node *head;

void initializeLinkedList() {
    static unsigned int i;

    nodePtr = (node*)malloc(sizeof(node));
    i = 0;

    nodePtr->nextPtr = (node*)malloc(sizeof(node)); 
    nodePtr->value = i;
    head = nodePtr;
    for (i = 1; i < 5; i++) {
        nodePtr->nextPtr = (node*)malloc(sizeof(node)); 
        nodePtr->value = i;
     }                
    nodePtr->nextPtr = NULL;
}

 void printLinkedList() {
    static unsigned int i;

    i = 0;   
    nodePtr = head;
    while (nodePtr->nextPtr != NULL) {
        printf("Value of ptr is %p \n", nodePtr->nextPtr);
        printf("Value is %d \n", nodePtr->value);
    }
}

I think I am not setting the pointers properly.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
user968000
  • 1,765
  • 3
  • 22
  • 31
  • 1
    [Don't cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also, please use whitespace and indentation properly. –  Feb 11 '13 at 21:11
  • You're right that your initialization is wrong. You're just overwriting the first node over and over. – Carl Norum Feb 11 '13 at 21:13
  • did you forget about nodePtr = nodePtr->nextPtr; ? – oleg_g Feb 11 '13 at 21:13

1 Answers1

4

This:

for (i = 1; i < 5; i++) {
    nodePtr->nextPtr = malloc(sizeof(node)); 
    nodePtr->value = i;
}

allocates a node four times, then it always overwrites the same element, since you don't update nodePtr. It should be

for (i = 1; i < 5; i++) {
    nodePtr->nextPtr = malloc(sizeof(node)); 
    nodePtr->value = i;
    nodePtr = nodePtr->nextPtr;
}

instead (and not just in this particular case - look for this everywhere in your code and fix it, else you'll end up with all those more or less funny results of undefined behavior...).

Furthermore, in printLinkedList(),

while(nodePtr->nextPtr != NULL)

should be

while(nodePtr != NULL)

else you'll be dereferencing NULL upon the last iteration (and BANG!)