gpt4 book ai didi

linux - 我正在尝试编写一个抽象数据类型来使用链表表示整数项集。我遇到段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:18 25 4
gpt4 key购买 nike

我正在尝试编写一个抽象数据类型来使用链接列表表示整数项集。我遇到段错误 (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);
}

最佳答案

看这里..

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));

关于linux - 我正在尝试编写一个抽象数据类型来使用链表表示整数项集。我遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com