do while循环中出现分段错误(核心已转储)

时间:2020-05-11 21:23:19

标签: c

以下代码创建一个链接列表,并以整数作为数据结构。我调用函数scanf将数字存储在do while循环中。然后,它说出列表有多少个节点,最后打印列表中找到的所有元素。但是,对于第二部分,我需要删除列表中的某些元素(此部分尚未完成),但是我需要提示用户是否要这样做。问题:我正在尝试测试是否输入与Y或N不同的任何东西,然后它一直询问用户是否要删除列表中的元素。我收到“ SIGSEGV”错误,我不知道为什么。有人可以帮我吗?变量char * answer的声明似乎有问题

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


typedef struct Node {
    int number;
    struct Node * next;
} NODE;

NODE * createNode( int number )
{
    NODE * newNode;

    newNode = malloc( sizeof(NODE) );
    newNode->next = NULL;
    newNode->number = number;

    return newNode;
}

int main( int argc, const char * arg[] )
{
    NODE * start = NULL, * current, *next;
    char goOn;
    int listSize = 0, number;

    do {
        printf( "List has %d nodes. Enter another number (0 to exit the prompt)\n", listSize );
        scanf("%d", &number );
        if ( number ) {
            if ( !start ) {
                start = createNode( number );
                listSize++;
            } else {
                current = start;
                while ( current->next ) {
                    current = current->next;
                }
                current->next = createNode( number );
                listSize++;
            }
            goOn = 1;
        } else {
            goOn = 0;
        }
    } while ( goOn );

    current = start;
    printf( "List contains the numbers: \n" );
    while (current) {
        printf( "%d", current->number );
        printf( current->next ? ", " : "\n" );
        current = current->next;
    }

    current = start;
    while (current) {
        next = current->next;
        free( current );
        current = next;
    }

    char *answer;
    do {
    printf("Do you want to delete element(s) of the list?");
    scanf("%s", answer);
    }while(answer != "Y" || answer != "N");
    return 0;
}

1 个答案:

答案 0 :(得分:3)

您要声明一个指针,但没有为其分配任何内存。

您还使用==比较字符串。为此,您必须使用strcmp()

这里不需要使用字符串。使用单个字符。正确的条件运算符是&&,而不是||(请参阅Why non-equality check of one variable against many values always returns true?)。

char answer;
do {
    printf("Do you want to delete element(s) of the list?");
    scanf(" %c", &answer);
}while(answer != 'Y' && answer != 'N');