c - 链表按字母顺序排序,c中的段错误

标签 c sorting

我正在尝试按字母顺序对链接列表进行排序,但我的排序函数出现seg failure。如何按字母顺序对列表进行排序。

typedef struct  s_file
{
    char        *file_name;
    struct      s_file *next;
}               t_file;

void    sort_alpha(t_file **begin_list)
{
    t_file  *list;
    char    *tmp;

    list = *begin_list;
    if (list)
    {
        while (list)
        {
            if (strcmp(list->file_name, list->next->file_name) < 0)
            {
                tmp = list->file_name;
                list->file_name = list->next->file_name;
                list->next->file_name = tmp;
            }
            list = list->next;
        }
    }
}

最佳答案

在行

      if (strcmp(list->file_name, list->next->file_name) < 0)

      // list->next could be NULL so
      // list->next->file_name could give seg fault

需要保护。可能的解决方案:

void sort_alpha(t_file **begin_list)
{
t_file  *list;
char    *tmp;

list = *begin_list;
if (list)
{
    while (list && list->next)
    {

        if (strcmp(list->file_name, list->next->file_name) < 0)
        {
            tmp = list->file_name;
            list->file_name = list->next->file_name;
            list->next->file_name = tmp;
        }
        list = list->next;
    }
}
}

关于c - 链表按字母顺序排序,c中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759093/

相关文章:

c - 从两个数组和一个整数 C 语言中返回一个值

javascript - 如何对不同属性执行自定义主干排序?

javascript - 对两个关联数组/堆栈进行排序

java - Java 中通过属性对数组进行排序

android - 如何在 C/C++ 中增强 YUV420P 到 RGB 的转换?

c - 用于将指针转换为线性地址的 FP_SEG 和 FP_OFF 的替代方案

c - 如何优化KASUMI密码S盒?

c - 我是 C 新手。第二个 for 循环永远不会结束为什么会这样

javascript - 实用地将日期字符串转换为 yyyy-mm-dd

asp.net - 对对象集合或列表进行数据绑定(bind)时对 gridview 进行排序