c - 使用 while 循环检查 struct 的内容

标签 c

我试图将一个节点附加到链表中,但是,当我使用 while 循环来检查“link”是否设置为 NULL 时,循环在不应该执行的时候被执行。

就好像“cursor->link”未设置为 NULL 并且 while 循环内的代码正在执行,我将 print 语句放在那里只是为了测试它,即使“cursor->link”也正在执行>链接”设置为 NULL。创建函数返回一个“node*”。

编辑 - 我向大家道歉,我在深夜发布了这个问题,我想我可能没有处于最佳状态来正确表达自己。另外,我对如何处理和使用链接列表仍然有点困惑(正如我的代码可能显示的那样)。我已经获得了一个可以使用的模板(如功能追加和显示是预设的,我必须按原样使用它们)。编译器不会按原样对代码发出任何警告。然而,程序仍然在 While 循环周围的追加函数中崩溃。

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

typedef struct node {
int data;
struct node * link;
} node;

node* create(int data,node* link) {

    node* newNode = (node*)malloc(sizeof(node));

    newNode->data = data;
    newNode->link = link;

    return newNode;
}

void append ( node **, int ) ;

void display ( node * ) ;

int main() {

   node *p ;
   p=NULL;
   int n;
   char ch[10];

   do {
       printf("Enter the value\n");
       scanf("%d",&n);
       append(&p,n);
       printf("Do you want to add another node? Type Yes/No\n");
       scanf("%s",ch);
   }while(!strcmp(ch,"Yes"));

   printf("The elements in the linked list are");

   display(p);

   printf("\n");
   return 0;
}

/* adds a node at the end of a linked list */
void append ( node **q, int num ){

   node *cursor;

   if (*q == NULL) {

       *q = create(num, NULL);
       node *cursor = *q;
   }

   while(cursor->link != NULL) {

       printf("1\n");
       cursor = cursor->link;
   }

       node* newNode = create(num, NULL);
       cursor->link = newNode;
}

void display ( node *q ){

   node *cursor = q;

   while(cursor->link != NULL) {
           printf(" %d", q->data);
           cursor = cursor->link;
       }
   printf(" %d", cursor->data);
}

最佳答案

正如 Ry 提到的,问题在于您在 while 循环中使用的游标,它从未初始化。相反,当 *q 为 null 时,您将创建一个具有相同名称的新变量。我在您的代码中看到另一个问题,当列表为空时,您将添加新节点两次。首先在 null 检查条件中,然后在 while 循环之后。

要修复移动此行 “节点*光标=*q” 在 if 条件之外并添加一个 return 来代替。也删除这一行 “节点*光标”

注意::我假设您的创建方法没有问题。

关于c - 使用 while 循环检查 struct 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55944160/

相关文章:

c - 查找最长的字符串名称和长度

c - 带指针的结构的 malloc(重新访问)

c - epoll 事件不会引发 SIGIO

c - 什么是用于嵌入式系统的良好 C 内存分配器?

c - 使用不带字符串化的#define 参数名称

c - 解析器在 C 中生成段错误

c - 为什么是 ISO_C_BINDING

c - 如何处理 HWUT 中迭代器的极简示例中的错误

c - 右移二进制进行除法

c - 如果我不使用 "Process returned 18 (0*12)",为什么它总是显示 "return 0"?