如何解决在其他结构中使用指针进行结构化分段错误
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));
然后可以填充并使用它们。您还需要记住以后释放它们。
,我分配了内存,但是在打印结果时遇到问题。 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。