Stuck on "cast discards 'const' qualifier"
I have a code:
int cmp_str_and_dirent(const void *key, const void *elem) {
const char *name = key;
const struct dirent *de = *(const struct dirent**)elem;
^ Cast discards `const` qualifier
return strcmp(name, de->d_name);
}
struct dirent **entries;
file_count = scandir(path, &entres, NULL, alphasort);
struct dirent *found = bsearch(name, entries, file_count,
sizeof(struct dirent*), cmp_str_and_dirent);
So the question is: How to properly do dereferencing from const void * if that pointer is actually pointer to a pointer to a structure?
compiler gcc 11.2.1, using -std=gnu11
Although C allows type qualifiers such as
constto be placed before type names so as to allow their usage to appear similar to storage classes such asregister, this obscures their meaning when they are used in pointer declarations. Althoughregister int *pwould declare a pointer withregisterstorage class that identifies anint, the definitionconst int *qdefines a non-const pointer to aconst int. Moveconstqualifiers after the type name, and recognize that their placement relative to asterisks is significant, and all will become clear. I think what you want is to convert the pointer to a(struct dirent const * const *), i.e. a pointer to a read-only pointer to a read-only object.