user968000
user968000

Reputation: 1843

Display of singly linked list

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.

Upvotes: 0

Views: 364

Answers (1)

user529758
user529758

Reputation:

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!)

Upvotes: 4

Related Questions