Question

The printlist function in the following code does not work. When I pass a node pointer from the main function the value is not passed.

void printlist(node *head)
{

    node *current=head;

    while(current!=NULL)
    {
        printf("\n %d",current->data);
        current=current->next;
    }
}


int main(void)
{
    int ch=1;
    int choice=1;
    while(ch=1)
    {
        node *head;
        head=(node*)malloc(sizeof(node));
        printf("Press 1 for create list \n2 for display \n3 for add at end of list \n");
        scanf("%d",&choice);`


        switch(choice) {
        case 1:
            head=createlist();
            node *current=head;
            break;

        case 2:
            printf("Welcome to list printer");
            printlist(head);
            break;
        }
    }
}  

** Note:-create list works fine i have not put it here to reduce the question size,i have tried using the same print technique inside the main function and it has worked like a charm.Its only when I tried to implement it as a function that the error started.

Was it helpful?

Solution

Your primary problem is here:

while(ch=1)
    {
        node *head;

head is local to the while block. After creating a new list on case 1, that variable will go out of scope and disappear before the loop comes round to give you a chance to print it. So you're just passing uninitialized memory to printlist(). You need:

node * head;
while (ch=1) {

There are numerous other problems with your code:

  • ch=1 means the while loop will never end, you don't seem to ever change ch anyway.
  • you malloc() memory for head, but then overwrite the value of head when you call createlist() and lose that memory, without having ever used it.
  • node * current is never used
  • don't cast the return from malloc()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top