简体   繁体   中英

scanf not running multiple times in loops C

so this is my code for creating and printing a linked list. I wrote this code in atom ide but when i run the code there is a problem with asking input as shown in output below.

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

typedef struct node {
    int data;
    struct node *next;
};

struct node * createl(int n);

void printlist(struct node* head2);

int main() {
    struct node *mainhead;
    int n;

    printf("Enter the number of nodes : " );
    scanf("%d",&n );
    mainhead=createl(n);
    printlist(mainhead);
    getch();
    return 0;
}

void printlist(struct node * head2)
{
    struct node *ptr;
    ptr=head2;
    printf("\nLinked List : \n" );
    while (ptr!=NULL) {
        printf("%d => ",ptr->data);
        ptr=ptr->next;
    }

}


struct node * createl(int n)
{
    struct node *head=NULL,*iso=NULL,*p=NULL;
    int i=0;
    while(i<n){
        setbuf(stdout,NULL);
        iso=(struct node*)malloc(sizeof(struct node));
        printf("\nEnter data in node no. %d :",i+1);
 
        scanf("%d",&(iso->data));
        iso->next=NULL;

        if (head=NULL)
        {
            head=iso;
        } else {
            p=head;
            while (p->next!=NULL) {
                p=p->next;
            }
            p->next=iso;
        }
        i++;
    }
    return head;
}

The expected Output should be:

Enter number of node : 5
Enter data in node no 1 : 1
Enter data in node no 2 : 2
Enter data in node no 3 : 3
Enter data in node no 4 : 4
Enter data in node no 5 : 5

Linked List: 1 => 2 => 3 => 4 => 5

But the actual output it shows is:

Enter the number of nodes : 4
Enter data in node no. 1 : 1
program ends 

The code is setting head to NULL when it should be evaluating it for NULL :

Change this

if (head=NULL)//assignment, leaves head NULL when executed

to

if (head==NULL)//evaluates head, but does not change it.

3 additional suggestions:

  • When memory created using malloc() is no longer needed, it should be freed.

    ....
    getch();
    //free Each node that was created

  • Casting the return of malloc() in C is not recommended .

    //iso=(struct node*)malloc(sizeof(struct node));
    iso=malloc(sizeof(struct node));

  • getch() is POSIX only, and is not portable. A portable alternative is getchar()

The problem is in your createl function, in the if case. You need to change from if (head = NULL) to if (head == NULL) and it will work.

Another 2 things:

  1. In the function printlist , your last element will print x => and not x .
  2. You need to free your struct node* mainhead at the end of the main.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM