Linux 我试图编写一个抽象数据类型,用链表表示整数项集。我遇到了一个分割错误

Linux 我试图编写一个抽象数据类型,用链表表示整数项集。我遇到了一个分割错误,linux,struct,linked-list,Linux,Struct,Linked List,我试图编写一个抽象数据类型,用链表表示整数项集。我遇到分段错误(linux)或程序崩溃(windows),无法理解我的代码出了什么问题 #include<stdio.h> #include<stdlib.h> struct linkedListElement{ int data; struct linkedListElement * next; }; struct linkedListSet { struct linkedLi

我试图编写一个抽象数据类型,用链表表示整数项集。我遇到分段错误(linux)或程序崩溃(windows),无法理解我的代码出了什么问题

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

struct linkedListElement{
    int data;
    struct linkedListElement * next;
        };

struct linkedListSet {

    struct linkedListElement * header;
    struct linkedListElement * current;
    struct linkedListElement * temp;



         };

struct linkedListSet * createdSet (){

struct linkedListSet * newSet = malloc(sizeof(struct linkedListSet));

newSet->header->data = 0;
newSet->header->next = NULL;

return newSet;

                 };


int main(){
//create set
    struct linkedListSet * firstSet = createdSet();


return (0);
}   
#包括
#包括
结构链接列表元素{
int数据;
结构linkedListElement*下一步;
};
结构链接列表集{
结构linkedListElement*头;
结构linkedListElement*当前;
结构linkedListElement*temp;
};
结构linkedListSet*createdSet(){
struct linkedListSet*newSet=malloc(sizeof(struct linkedListSet));
新闻集->标题->数据=0;
新闻集->标题->下一步=空;
返回新闻集;
};
int main(){
//创建集
结构linkedListSet*firstSet=createdSet();
返回(0);
}   
看看这里

struct linkedListSet * createdSet (){

    struct linkedListSet * newSet = malloc(sizeof(struct linkedListSet));

    // newSet->header is just a pointer - doesn't point to anything valid!
    newSet->header->data = 0;
    newSet->header->next = NULL;

    return newSet;

};
您还需要确保指针是有效的。你可以这样做:

newSet->header = malloc(sizeof(struct linkedListElement));

您已经创建了一个未初始化的linkedListSet,然后取消引用指针数据,然后单击next。这些不指向任何内存。您需要先分配linkedListElement,然后才能使用它。正确的初始化是:

struct linkedListSet * createSet ()
{
    struct linkedListSet * newSet = malloc(sizeof(struct linkedListSet));
    newSet->header = NULL;
    newSet->current = NULL;
    newSet->temp = NULL;
    return newSet;
};

哪些特定的代码行在这里不起作用?(我只是好奇,因为这里没有提到它,知道这一点可能会有用)。好的,谢谢你-我将尝试为标题指向的linkedListElement分配空间并初始化它。太好了-这很有意义。感谢您花时间编写此代码