首页 > 解决方案 > 为什么在更改循环条件时会出现分段错误?

问题描述

我正在学习链接列表,并且在构建它的循环时遇到了麻烦。这是我的导致分段错误的代码。

struct node {char data[20]; struct node *next;};
struct node *head = NULL, *newNode = NULL, *p;

char temp[20];

while (temp[0] != 0)
    {   
        temp[0] = 0;
        printf("Enter a word: ");
        scanf("%s", temp);

        newNode = malloc(sizeof(struct node));
        strcpy(newNode->data, temp);
        newNode->next = head;
        head = newNode;
    }

当我用它替换temp[0] != 0temp[0] == 0时不会导致分段错误。这里发生了什么?为什么相同的检查倒置不起作用?

标签: cwhile-looplinked-listsegmentation-fault

解决方案


推荐阅读