Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading