-2

This is a program to print two link lists using one function. I have used two functions i.e create and display.Create() is to create the linklist and display() to display the result of linklist.

But this code is printing NULL. I'm not not getting where is the error???

    `#include<stdio.h>
#include<conio.h>

struct node
{
    int data;
    struct node* next;

}
*start=NULL,*start1=NULL;
//to create the linklist
struct node* create(struct node* ptr)
{       int ch;
    do
    {
    struct node* new_node=(struct node*)malloc(sizeof(struct node));
    struct node* current;
    printf("enter the data\n");
    scanf("%d",&new_node->data);
    new_node->next=NULL;
    if(ptr==NULL)
    {
        ptr=new_node;
        current=new_node;
    }
    else
    {
    current->next=new_node;
    current=new_node;
    }
    printf("Do u want to add more ");
    scanf("%d",&ch);
    }while(ch!=0);
    return ptr;
}
//to display the linklist
 void display(struct node* temp)
 {

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

 }
 int main()
 {
    clrscr();
    create(start);
    display(start);
    printf("\n 2nd linklist\n");
    create(start1);
    display(start1);
    getch();
    return 0;
 }
Priya
  • 1
  • How about you never save the results of your list creations to `start` and `start1` (assuming they even work, I stopped reading once I saw that). – WhozCraig Jul 30 '15 at 06:16
  • Please get out of turboC or whatever you are using. conio.h doesn't even exist in GCC. Then read about pointers and look at your code. Think it through.. its not displaying anything, so are you saving the data in correct place. Use printf to check when you are saving data – Imdad Jul 30 '15 at 06:20
  • You should definitely read [this article](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Jabberwocky Jul 30 '15 at 06:59

1 Answers1

0

First problem

current must be declared outside the do/while loop, otherwise you will get undefined behaviour because there is no guarantee that current will keep it'svalue from one iteration to the next. However with certain compilers you may get away with it.

Second problem

Calling create(start); will not modify start because variables in C are passed by value. You need to write start = create(start);. See also this SO question. In your program start is still NULL after the call to the create function. You could have found out that easily by yourself.

Community
  • 1
  • 1
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115