【问题标题】:Error(Id) returned 1 exit statusError(Id) 返回 1 个退出状态
【发布时间】:2017-09-04 12:12:20
【问题描述】:

我试图遍历单链表的程序,出现错误,似乎 do 和 while 循环没有正确应用,请检查

该程序在我尝试使用 do while 和指针遍历的位置下方。

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

int main()
{
    char ch;
    struct node
    {
        int info;
        struct node *next;
    };
    typedef struct node node;
    node *start, *ptr, *ne;
    ptr=NULL;
    int count=0;
    do
    {
    ne=(node*) malloc(sizeof(node));
    printf("\nEnter Data: ");
    scanf("%d",&ne->info);
    if(ptr!=NULL)
    {
    ptr->next=ne;
    ptr=ptr->next;
    }
    else {
    start=ne;
    ptr=ne;
    }
    printf("\nDo you wish to continue?\n ");
    scanf("%c",&ch);
      }while(ch=='y'|| ch=='Y');
      ptr->next=NULL;
      printf("The linked list is: ");
      ptr=start;
      while(ptr!=NULL)
      {
      printf("\t%d",&ptr->info);
      ptr=ptr->next;
      count++;
      }
      printf("\nTotal number of elements: %d",count);
    return(0);     


}

【问题讨论】:

  • 如果链接器返回错误(您没有复制到帖子中),您的程序将无法运行。所以问题不在于没有“应用”循环。
  • 在询问构建错误时,总是在问题正文中包含 complete 错误输出。完整、完整,包括可能的信息说明,无需编辑,作为(复制粘贴)文本

标签: c++ c data-structures linked-list


【解决方案1】:

改变

printf("\t%d",&ptr->info);

 printf("\t%d",ptr->info);

另外我不建议在typedef struct node node; 中使用同名“节点” 但这仍然不是问题。

编辑:

我还发现您的代码有问题:

改变

printf("\nDo you wish to continue?\n ");
scanf("%c",&ch);

printf("\nDo you wish to continue?\n ");
getchar();
scanf("%c",&ch);

或者

你也可以改成

printf("\nDo you wish to continue?\n ");
scanf(" %c",&ch); //add a space before %c

为什么会导致错误?

在程序中,当您尝试使用'printf()' 打印任何内容时,缓冲区中会留下一个空格,因此我们必须读取它并忽略它,否则将为 ch 分配空格。要读取空白并忽略,我们有两个选项,如上所述。尝试任何一个。

【讨论】:

  • 即使它工作它也不能让我输入超过一个数字,我输入一个数字并显示摘要
  • @AyushShrivastava 检查我的编辑,如果有效,请竖起大拇指.. :-)
猜你喜欢
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 2013-07-17
  • 2018-04-16
  • 1970-01-01
相关资源
最近更新 更多