在do while循环中出现分段故障(核心转储)。

问题描述 投票:0回答:1

下面的代码创建了一个链接列表,用一个整数作为数据结构。我在do while循环中调用函数scanf来存储数字。然后它说这个列表有多少个节点,最后打印出在列表中找到的所有元素。然而,对于第二部分,我需要删除列表中的一些元素(这部分还没有完成),但我需要提示用户是否愿意这样做。问题:我试图测试如果我输入任何与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;
}
c
1个回答
3
投票

你声明了一个指针,但没有为它分配任何内存。

你还使用了 == 来比较字符串。你必须使用 strcmp() 对于这个。

这里不需要使用字符串。使用单个字符。而正确的条件操作符是 &&,不 || (见 为什么一个变量对多个值的非等价检查总是返回真?).

char answer;
do {
    printf("Do you want to delete element(s) of the list?");
    scanf(" %c", &answer);
}while(answer != 'Y' && answer != 'N');
© www.soinside.com 2019 - 2024. All rights reserved.