【问题标题】:Struct with pointer in other struct (segmentation fault)在其他结构中带有指针的结构(分段错误)
【发布时间】:2021-02-21 11:16:27
【问题描述】:

所以,我有这 2 个结构和一个全局变量

struct Tasks{

    int tid;                      
    int difficulty;               
    struct Tasks *next;           
};

struct Head_GL{

    int tasks_count[3];           
    struct Tasks *head;           
};

struct Head_GL *tasks_head;

我必须创建一个按难度加入顺序的链接列表。如何进行比较和阅读难度。我这样做了tasks_head->head->difficulty 并给了我分段错误

【问题讨论】:

  • 您需要先为它们分配内存。
  • tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));像这样?
  • 你还需要分配tasks_head
  • 所以在分配 tasks_head->head 之前我必须分配 tasks_head tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
  • 你可以放弃演员表,他们没用:(struct Tasks*)malloc(sizeof(struct Tasks)) -> malloc(sizeof(struct Tasks))

标签: c pointers data-structures linked-list


【解决方案1】:

您需要创建每个项目:

tasks_head = calloc(1, sizeof(struct Head_GL));
tasks_head->head = calloc(1, sizeof(struct Tasks));

然后您可以填充和使用它们。您还需要记住稍后释放这些。

【讨论】:

  • 结构体(他是否也需要 typedefs...)
  • 他们应该是struct Head_GLstruct Tasks
【解决方案2】:

我分配了内存,但打印结果时遇到问题。 main (tasks_head->head->tid) 中 printf 中的分段错误。有什么帮助吗?

struct Tasks *new=(struct Tasks*)malloc(sizeof(struct Tasks));


tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));

tasks_head->tasks_count[0]=0;
tasks_head->tasks_count[1]=0;
tasks_head->tasks_count[2]=0;
tasks_head->head->difficulty=0;
tasks_head->head->tid=0;
tasks_head->head->next=NULL;

if(new==NULL)
    return 0;
new->tid = tid;
new->difficulty = difficulty;
new->next = NULL;

if(difficulty==1)
    tasks_head->tasks_count[0]++;
else if(difficulty==2)
    tasks_head->tasks_count[1]++;
else
    tasks_head->tasks_count[2]++;


if(tasks_head==NULL){
    tasks_head->head = new;
    return 1;
}
if( tasks_head->head->difficulty > difficulty){
    new->next = tasks_head->head;
    tasks_head->head= new;
    return 1;
}
else{
    prev = tasks_head->head;
    temp = tasks_head->head->next;
    while(temp != NULL && temp->difficulty < difficulty){
        prev = temp;
        temp = temp->next;
    }
    if(temp==NULL){
        prev->next = new;
        return 1;
    }
    else{
        new->next = temp;
        prev->next = new;
        return 1;
    }
}

}

int main(){

printf("hello1\n");

if(1==insert_task(1,1))
    printf("alo");

if(1==insert_task(4,1))
    printf("alo");

if(1==insert_task(3,2))
    printf("alo\n");


printf("%d\n",num);

for(int i=0; i<num; i++){
    printf("%d\n",tasks_head->head->tid);
    tasks_head->head=tasks_head->head->next;
}

return 0;

}

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多