cgccgcc11

C - const qualifier discard when const void* is actually struct**


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


Solution

  • Although C allows type qualifiers such as const to be placed before type names so as to allow their usage to appear similar to storage classes such as register, this obscures their meaning when they are used in pointer declarations. Although register int *p would declare a pointer with register storage class that identifies an int, the definition const int *q defines a non-const pointer to a const int. Move const qualifiers 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.