【问题标题】:Why this C program execution stops working while inputting through scanf()?为什么这个 C 程序执行在通过 scanf() 输入时停止工作?
【发布时间】:2015-08-03 09:30:07
【问题描述】:

这是一个简单的 C 程序,用于创建和显示单链表。creat() 函数以节点数据为参数在前一个节点之后创建一个新节点。display() 函数打印链表.此程序片段无法正常工作:

    for(b=1;b<=5;b++) {
    scanf("%d ",&a);
    creat(a);
    }

如果通过 scanf() 插入两个或三个值,则执行将停止工作。 那有什么问题? 如果你跳过 scanf() 并像下面这样放置语句,它会起作用:

    for(b=1;b<=5;b++) {
    creat(7);
    }  

主代码:

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

struct node
{
int data;
struct node *next;
} *head=NULL;

typedef struct node Node;

void creat(int d);
void display();

int main()
{
int a,b;
 printf("Input data to build a linked-list:\n");
  for(b=1;b<=5;b++) {
    scanf("%d ",&a);    /*Error statement maybe*/
    creat(a);

}
printf("The list is:-\n");

display();
return 0;

}
void creat(int d)
{

Node *new,*curr;

new=(Node *) malloc(sizeof(Node));
new->data=d;
new->next=NULL;

if(head==NULL)
{
    head=new;
    curr=new;
}
else
{
    curr->next=new;
    curr=new;
}

 }
void display()
{
Node *p;
p=head;
while(p)
{
    printf("%d--->",head->data);
    p=p->next;
}
printf("NULL\n");
}

【问题讨论】:

  • curr-&gt;next=new; : curr 是局部变量。 scanf("%d ",&amp;a); --> scanf("%d",&amp;a);
  • 我投票决定将此问题作为题外话结束,因为链表存在常见错误之一(更改为本地 var 不传播给调用者),并且没有调试。
  • 你能告诉我如何修复这个错误吗?

标签: c linked-list scanf


【解决方案1】:

其实问题是由函数creat()-

else 此函数中的部分正在产生问题。应该是这样的-

else
{
    curr=head;
    while(curr->next!=NULL)
      {
          curr=curr->next;
      }
    curr->next=new;
}

遍历到最后一个节点并添加新节点。

还有scanf

  scanf("%d ",&a);    /*Error statement maybe*/
           ^Remove the space.

同样在函数void display()

while(p)
{  
    printf("%d--->",head->data);
    p=p->next;
 }

您正在打印head-&gt;data,但它没有递增到下一个,而是将p 设置为p-&gt;next。因此,此函数不会打印整个链接列表。

printf应该是这个-

    printf("%d--->",p->data);

【讨论】:

    【解决方案2】:

    尝试在 %d 之后不带空格 - scanf 可能相当脆弱....

    scanf("%d",&a);
    

    【讨论】:

      【解决方案3】:
      1. } *head=NULL;改成} *head=NULL, *curr;

      2. scanf("%d ",&amp;a);更改为scanf("%d",&amp;a);

      3. Node *new,*curr;更改为Node *new;

      4. printf("%d---&gt;", head-&gt;data);更改为printf("%d---&gt;", p-&gt;data);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-31
        • 2021-12-18
        • 1970-01-01
        相关资源
        最近更新 更多