首页 > 解决方案 > C中的链表。分段错误

问题描述

#include <stdio.h>


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

typedef struct mychar Mychar;
typedef Mychar *MycharPtr;


void insert(MycharPtr *, char );
void printlist(MycharPtr);


int main(){
    MycharPtr startPtr = NULL;

    char b = 'b';

    insert(&startPtr, b);

    printlist(startPtr);
}

void insert(MycharPtr *sPtr, char newvalue){

    MycharPtr newlinkPtr;

    if (*sPtr == NULL){
        newlinkPtr->value = newvalue;
        newlinkPtr->nextPtr = NULL;
    }

    *sPtr = newlinkPtr;
}


void printlist(MycharPtr currentPtr){
    printf("%c", currentPtr->value);
}

我刚开始只添加一个字符。如果我连那个都做不到,我就不能继续做其他事情。

它给了我分段错误,但我真的不知道为什么。

另外,我仍然不明白为什么在insert通话中我应该写&但在printlist通话中我不应该写&

标签: cpointersdata-structuresstructlinked-list

解决方案


您实际上还没有为newlinkPtr. 因此,您只是取消引用并尝试写入未初始化的指针,从而导致未定义的行为。

insert,可以修改为:

MycharPtr newlinkPtr = malloc(sizeof *newlinkPtr);
if (!newlinkPtr) {
    perror("malloc");
    return;
}

...

这在某种程度上也说明了为什么对结构指针进行类型定义可能会误导并被认为是一种不好的做法。我建议避免它。


推荐阅读