Thread: Simple linked list example error.

  1. #1
    Registered User
    Join Date
    Nov 2014
    Posts
    45

    Simple linked list example error.

    Hello again.

    I was studying Linked list, I'm beginner. Where is my mistake ? Please help me.

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    struct listnode{
        int num;
        struct listnode *nextPtr;
    };
    typedef struct listnode ListNode;
    ListNode *head, *p;
    
    
    int main(){
    
    
        int choice = 1;
    
    
        p = (ListNode*)malloc(sizeof(ListNode));
    
    
        head = p;
        while(choice){
        printf("Enter number: ");
        scanf("%d",&p->num);
    
    
        p = p->nextPtr;
        p = (ListNode*)malloc(sizeof(ListNode));
    
    
        printf("Continue or break(1-0)");
        scanf("%d",&choice);
    
    
        }
        p->nextPtr = NULL;
        traverseTheList();
    return 0;
    }
    
    
    void traverseTheList(){
        p = head;
        printf("\n");
        printf("\n");
        while( p!=NULL ){
            printf("%d",p->num);
            p = p->nextPtr;
            printf("\n");
    
    
        }
    }

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Code:
    p = p->nextPtr;
    p = (ListNode*)malloc(sizeof(ListNode));
    This is not how you would append a node. Instead, try allocating memory to another variable, assign that value to "p->nextPtr", then advance "p".

    Not the most pretty way to go about it, but this should get you rolling. There are other issues, but you can start with that.

    Some general comments:

    • You should check that "malloc()" succeeds before trying to use the memory
    • You should be freeing any of the memory you allocate
    • You should not cast the return value of "malloc()": FAQ > Casting malloc - Cprogramming.com
    • If you define the function "traverseTheList()" after "main()", you should declare it before
    • You should not use global variables, but instead declare them where used and pass them to functions as needed

  3. #3
    Registered User
    Join Date
    Nov 2014
    Posts
    45
    thank you so much. that's fixed

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple add to linked list
    By c172spilot in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2011, 02:20 PM
  2. Simple Linked List Problem
    By Flamefury in forum C++ Programming
    Replies: 6
    Last Post: 03-20-2010, 07:38 PM
  3. Simple Linked List Error
    By guitarist809 in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2008, 10:15 PM
  4. Need help with simple linked list
    By Mahak in forum C++ Programming
    Replies: 5
    Last Post: 09-14-2006, 09:56 AM
  5. simple linked list
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 12-01-2005, 11:27 AM