为什么我的append()函数会导致段错误?

问题描述 投票:0回答:1
#include <stdio.h>


struct mychar {
    char value;
    struct mychar *nextPtr;
};

typedef struct mychar Mychar;


void instructions();
void append(Mychar **, char );
void printlist(Mychar *);


int main(){
    instructions();

    Mychar *startPtr = NULL;

    unsigned int choice;
    char newchar;
    do {
        scanf("%d",&choice);
        switch (choice) {
            case 1:
                printf("\nWrite the character you want to add.");
                printf("\n> ");
                scanf(" %c", &newchar);
                append(&startPtr, newchar);
                printlist(startPtr);
                break;
            case 2:
                break;
            default:
                printf("\nError, try again.\n");
                //main();
                instructions();
                break;
        }
    } while (choice!=3);
    printf("\n\nEnd of run.\n");
}


void instructions(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}


void append(Mychar **sPtr, char newvalue){
    Mychar *newlinkPtr = calloc (1, sizeof(Mychar));
    newlinkPtr->value = newvalue;
    newlinkPtr->nextPtr = NULL;

    Mychar *previousPtr = NULL;
    Mychar *currentPtr = *sPtr;

    while(currentPtr!=NULL && newvalue > currentPtr->value){
        previousPtr = currentPtr;
        currentPtr = currentPtr->nextPtr;
    }

    if (previousPtr){
        previousPtr->nextPtr = newlinkPtr;
        newlinkPtr->nextPtr = currentPtr;
    } else {
        *sPtr = newlinkPtr;
    }

}


void printlist(Mychar *currentPtr){
    printf("\n\nCurrent list:\n");
    while (currentPtr!=NULL){
        printf("%c", currentPtr->value);
        currentPtr = currentPtr->nextPtr;
    }
}

为什么我有这种行为?如果我运行该程序,则在输入1之后,它将打印“当前列表”并保持scanf输入处于打开状态,因此,只有在“当前列表”打印之后,我才能输入值。另外,只有在我用scanf输入字符后才应调用“当前列表”,因为函数printlist在scanf之后...但是实际上这是发生的情况:

Select operation. 1 to add, 2 to remove, 3 to exit.
> 1

Write the character you want to add.
> a


Current list:
ab

Write the character you want to add.
> 

Current list:
abc

Write the character you want to add.
> 

Current list:
abcd

Write the character you want to add.
> 

Current list:
abcd
c struct linked-list printf scanf
1个回答
0
投票

此课程的目的是始终检查scanf是否返回0,至少还建议使用EOF检查,并根据代码事件的顺序采取相应措施,并非如此在那里,通过一些调整,您可以得到不错的,不好的输入证明,I / O序列:

© www.soinside.com 2019 - 2024. All rights reserved.