I have a piece of C code that looks like this:
const char (*foo)[2] = bar();
Now bar() is a function that returns a (const void *). How do I properly cast this const pointer? The code produces this warning from GCC :
"initialization discards qualifiers from pointer target type".
Here are some of my unsuccessful attempts:
const char (*foo)[2] = (const char *)bar();
const char (*foo)[2] = (const void **)bar();
The original code does work, I just can't get rid of the warnings by properly casting the return value.
EDIT : This has been suggested:
const char (*foo)[2] = (const char (*)[2])bar();
It appears to be correct, but GCC gives this warning :
"cast discards qualifiers from pointer target type"
which is nearly identical to the original warning.
EDIT 2 : OK, I think I've got it. The real problem here is the ( const void * ) definition of bar(). The const in the definition (const char( * )[2]) refers to the elements of the array, not the pointer to the array. This type definition is essentially an array, which when represented by a void pointer is not const. The real answer is that a ( const void * ) loses its const-ness when cast to (const char ( * )[2]).
constarray type (not an array ofconst). The former is not possible in C (although they might as well be the same, the lack of lifting is arguably a bug in the standard). See my answer below for relevant links.