簡體   English   中英

scanf 沒有在循環中多次運行 C

[英]scanf not running multiple times in loops C

所以這是我創建和打印鏈接列表的代碼。 我在原子 ide 中編寫了這段代碼,但是當我運行代碼時,詢問輸入時出現問題,如下面的 output 所示。

#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;
}

預期的 Output 應該是:

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

鏈表:1 => 2 => 3 => 4 => 5

但它顯示的實際 output 是:

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

當它應該為NULL評估它時,代碼head設置為NULL

改變這個

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

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

3條補充建議:

  • 當不再需要使用malloc()創建的 memory 時,應將其釋放。

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

  • 不推薦在 C 中轉換malloc()的返回值

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

  • getch()僅適用於POSIX ,不可移植。 一個可移植的替代方法是getchar()

if情況下,問題出在您的createl function 中。 您需要從if (head = NULL)更改為if (head == NULL)並且它將起作用。

另外2件事:

  1. printlist打印列表中,您的最后一個元素將打印x =>而不是x
  2. 您需要在 main 的末尾釋放您的struct node* mainhead

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM