Home > database >  Segmentation Fault 11 when using a compare function in qsort()
Segmentation Fault 11 when using a compare function in qsort()

Time:05-26

I have an array of struct dir_item and I want to sort it using qsort. Using the following code I get a Segmentation Fault 11.

I would like to know:

  • How to fix this issue?
  • Why I have this issue in the first place
struct dir_item
{
    char name[NAME_MAX];
    int is_dir;
};

struct app_state
{
    char cwd[PATH_MAX];
    struct dir_item *dir_entries;
    int dir_entries_total;
    int user_highlight;
    int user_key_pressed;
};



int compare(const void *d1, const void *d2)
{
    return (strcmp((*(struct dir_item **)d1)->name,
                   (*(struct dir_item **)d2)->name)); // I THINK THE ISSUE IS HERE, BUT NOT SURE WHY
}

qsort(dir_entries, sizeof(dir_entries), sizeof(struct dir_item), compare);

I have tried this version, but does not sort (but does not get an error)

int compare(const void *d1, const void *d2)
{
    const struct dir_item *a = (struct dir_item *)d1;
    const struct dir_item *b = (struct dir_item *)d2;
    return strcmp(a->name, b->name);
}

CodePudding user response:

You've got too many *, simply cast d1 and d2 to struct dir_item* and dereference:

int compare(const void *d1, const void *d2)
{
    return (strcmp(((struct dir_item *)d1)->name,
                   ((struct dir_item *)d2)->name));
}

Demo

  •  Tags:  
  • c
  • Related