c-其他结构中有指针的结构(分段错误)



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

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 = calloc(1, sizeof(struct Head_GL));
tasks_head->head = calloc(1, sizeof(struct Tasks));

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

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

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("hello1n");
if(1==insert_task(1,1))
printf("alo");
if(1==insert_task(4,1))
printf("alo");
if(1==insert_task(3,2))
printf("alon");

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

}

相关内容

  • 没有找到相关文章