Search code examples
cpointerstypesqualifiers

Why does calling a function that accepts a (const char * const **) with a char *** raise a -Wcast-qual flag?


If we have void foo(const char * const ** bar); and we call it with char *** bar = malloc(...); such as foo((const char * const **) bar); It returns:

error: to be safe all intermediate pointers in cast from ‘char ***’ to ‘const char * const**’ must be ‘const’ qualified [-Werror=cast-qual]

Trying to pass it in without casting results in a type warning, but passing a char * into a const char * works, I can also pass a char *** into a char ** const * function parameter, but I want more read-only qualifier than just a single level.

The intent is that the function assumes the entire pointer data and pointer being passed in are read-only, such that the pointer won't be written to in any way.

I understand that the flag is an extra one, but it's defined as:

-Wcast-qual

Warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a const char * is cast to an ordinary char *.

As far as I can tell, no type qualifier is being removed, rather we're adding type qualifiers to let the user know that the function doesn't change any data.

Why is the previously mentioned code triggering the extra warning -Wcast-qual? Is there a better way of going about passing a completely malloc'd triple pointer as a read-only function?


Solution

  • TL;DR: const char * const ** -> const char * const * const *

    To finish the question, answered in the comments by /users/2410359/chux (asked them to make a post, but they haven't). The solution was to use a const char * const * const * which does not trigger the -Wcast-qual flag. Basically what I had was not true read-only qualifiers, I needed another level.