R
RjY
I have a function whose (simplified) prototype looks like this:[1]
const void *get_data(int id);
For some values of id it is convenient to treat the resulting data as
pairs of bytes. To do this the existing code tries to cast the return
value to a pointer to an array of constant pairs of bytes
const unsigned char (*data)[2] = (void *)get_data(id);
and accesses using data[0] and data[1] for the byte pairs.
I thought it was odd that the const qualifier was being cast away, so I
took the cast out and tried to recompile. The compiler (GCC) then
reported
warning: initialization discards qualifiers from pointer target type
So, what's going on here? Why can't I assign a const void pointer to a
pointer to pairs of const unsigned chars? What's the proper thing to do?
Can I use a struct, such as
const struct { unsigned char b1,b2; } *data = get_data(id);
Is it guaranteed that there won't be padding between b1 and b2?
Or perhaps an array within a struct:
const struct { unsigned b[2]; } *data = get_data(id);
Both of these appear to work, at least on the machine in front of me,
but I would appreciate your guidance on what the standard has to say.
Thanks in advance.
[1] Implementation detail: given some identifier the function returns a
pointer to some arbitrary data in a memory-mapped container file, which
was opened read-only. Hence the const void * return type. However I hope
this is irrelevant.
const void *get_data(int id);
For some values of id it is convenient to treat the resulting data as
pairs of bytes. To do this the existing code tries to cast the return
value to a pointer to an array of constant pairs of bytes
const unsigned char (*data)[2] = (void *)get_data(id);
and accesses using data[0] and data[1] for the byte pairs.
I thought it was odd that the const qualifier was being cast away, so I
took the cast out and tried to recompile. The compiler (GCC) then
reported
warning: initialization discards qualifiers from pointer target type
So, what's going on here? Why can't I assign a const void pointer to a
pointer to pairs of const unsigned chars? What's the proper thing to do?
Can I use a struct, such as
const struct { unsigned char b1,b2; } *data = get_data(id);
Is it guaranteed that there won't be padding between b1 and b2?
Or perhaps an array within a struct:
const struct { unsigned b[2]; } *data = get_data(id);
Both of these appear to work, at least on the machine in front of me,
but I would appreciate your guidance on what the standard has to say.
Thanks in advance.
[1] Implementation detail: given some identifier the function returns a
pointer to some arbitrary data in a memory-mapped container file, which
was opened read-only. Hence the const void * return type. However I hope
this is irrelevant.