When I apply container_of macro to a C struct which contains an array of char, I got warning: initialization from incompatible pointer type.
Here is the codes:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
struct st {
int a;
char b;
char c[16];
void *p;
};
int main(void)
{
struct st t = {
.a = 101,
.b = 'B',
.c = "hello",
.p = NULL
};
char (*p)[16] = &t.c;
struct st *s = container_of(p, struct st, c);
return 0;
}
It seems that the type of __mptr is [], which is deduced by typeof(). However, ptr itself is type (*)[]. Obviously, they are not the same.
Besides, if I compile this code by clang, everything is OK. GCC seems have a more strict rule for type checking.
Q: How to correct this warning?
(*)[]is not a type, nor is[].[]stands for array type, and(*)[]stands for pointer to array.CONTAINING_RECORD, which doesn't use any GCC extensions, of course.container_ofmacro from the Linux kernel is somewhat deficient, but if you have to use it, and you know the member is an array, you can use an element of the array instead of the array itself. I.e.char *p = &t.c[0]; struct st *s = container_of(p, struct st, c[0]);