sorting - Linked list alphabetical sort, seg fault in c -
i'm trying sort linked list in alphabetical order, i'm getting seg fault
sorting function. how can sort list alphabetically.
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; } } }
in line
if (strcmp(list->file_name, list->next->file_name) < 0) // list->next null // list->next->file_name give seg fault
a protection needed. possible solution:
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; } } }
Comments
Post a Comment