我一直在为一个学校项目工作,遇到了这个问题。
我正在尝试使用malloc存储列表,但是这段代码似乎不起作用。
column_t *sorted_insert(column_t *lst, char col3[MAX_SIZE], long int rep){
if (!lst || rep < lst->rep)
{
column_t *new = (column_t*) malloc(sizeof(column_t));
strcpy(new->col3, col3);
new->rep = rep;
new->next = lst;
new->previous = NULL;
lst = new;
if (lst->next)
lst->next->previous = new;
}else
{
lst->next = sorted_insert(lst->next,col3,rep);
lst->next->previous = lst;
}
return lst;
}
试图调用该函数:
sorted_insert(lst,"Test",0);
printf("%s",lst->col3);
并且没有输出。程序刚刚关闭。
更新@来自莫斯科的弗拉德
column_t *sorted_insert(column_t *lst, char col3[MAX_SIZE], long int rep){
if (lst == NULL|| rep < lst->rep)
{
column_t *new = malloc(sizeof(column_t));
if (new != NULL)
{
strcpy(new->col3, col3);
new->rep = rep;
new->previous = NULL;
new->next = lst;
if (lst != NULL)
lst->previous = new;
}
lst = new;
}else
{
column_t *new = sorted_insert(lst->next, col3, rep);
if (new != NULL)
{
lst->next = new;
new->previous = lst;
}
}
return lst;
}
将呼叫更改为:
lst = sorted_insert(lst,tmp->col3,w);
display(lst);
输出:
列表的输出现在是正确的,但是没有按升序排序。
我一直在为一个学校项目工作,遇到了这个问题。我正在尝试使用malloc存储列表,但是这段代码似乎不起作用。 column_t * sorted_insert(column_t * lst,char ...
似乎问题出在您如何调用该函数。