【问题标题】:scanf not running multiple times in loops Cscanf没有在循环C中多次运行
【发布时间】:2020-11-30 02:44:23
【问题描述】:

这是我创建和打印链接列表的代码。我在 atom ide 中编写了这段代码,但是当我运行代码时,询问输入时出现问题,如下面的输出所示。

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

预期的输出应该是:

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

但它显示的实际输出是:

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

【问题讨论】:

  • 请将实际输入输出以文字形式发布,而不是图片形式
  • 你不检查scanf的返回值,你怎么知道输入成功了?
  • @kartik30369 节省时间并启用所有警告。一个好的编译器会警告if (head=NULL)

标签: c eclipse singly-linked-list


【解决方案1】:

问题出在您的createl 函数中,在if 的情况下。你需要改变 if (head = NULL)if (head == NULL) 就可以了。

另外两件事:

  1. 在函数printlist 中,您的最后一个元素将打印x =&gt; 而不是x
  2. 您需要在 main 末尾释放您的 struct node* mainhead

【讨论】:

  • 同时释放mainhead指向的所有节点。
【解决方案2】:

代码是 设置 headNULL 当它应该 评估 NULL:

改变这个

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

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

3 条额外建议:

  • 当不再需要使用malloc() 创建的内存时,应该释放它。

    ....
    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() 仅是 POSIX,不可移植。一个可移植的替代方案是getchar()

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多