【发布时间】:2021-02-22 09:03:09
【问题描述】:
我有这段代码,我想打印每个节点的 tid。我在这个 for 循环中有分段错误
printf("%d\n",tasks_head->head->tid); 我不确定task_count[] 是否按我的意愿工作。我想在数组的每个位置保存一个counter++。
struct Tasks
{
int tid;
int difficulty;
struct Tasks *next;
};
struct Head_GL
{
int tasks_count[3];
struct Tasks *head;
};
struct Head_GL *tasks_head=NULL;
int num=0;
int insert_task(int tid, int difficulty){
num++;
struct Tasks *prev=NULL;
struct Tasks *temp=NULL;
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;
}
/*
for(int i=0; i<3; i++){
printf("%d",tasks_head->tasks_count[i]);
}*/
return 0;
}
【问题讨论】:
标签: c pointers data-structures linked-list