c++ - 错误(Id)返回 1 退出状态

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

我试图遍历单链表的程序,出现错误,似乎 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);     


}

最佳答案

改变

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 将被分配空格。要读取空白并忽略,我们有两个选择,如上所述。尝试任何一种。

关于c++ - 错误(Id)返回 1 退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306418/

相关文章:

java - 我需要能够在 eclipse 中找到行号和方法名称

c - 用于基本数据结构的库,例如 C 中的队列

c++ - fork 和 pipeline 错误文件描述符错误

c - "continue"和"break"用于静态分析

c++ - 为什么 C++ 编译器会在这里生成一个临时文件?

c++ - 如何在共享对象构建中包含子目录

algorithm - 人在受到限制的情况下从源地移动到目的地

java - 从未排序的数组中找出两个这样的元素,它们在不对数组进行排序的情况下具有最小差异

c++ - 使用 mpi 进行 sobel 边缘检测

c++ - 转换 : #define xxxxxx ((LPCSTR) 4)