我曾尝试使用 linux 内核中的 container_of 宏。
我得到的谷歌如下
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) \
({ const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define CONT(prt, type, mem) container_of((prt), type, mem)
struct test {
int a;
};
struct m {
int b;
struct test t;
int c;
};
int main(int argc, char *argv[])
{
/* existing structure */
struct m *ma;
ma = malloc(sizeof(struct m));
ma->t.a = 5;
ma->b = 3;
/* pointer to existing entry */
struct test *te = &ma->t;
struct m *m = CONT(te, struct m, t);
printf("m->b = %d\n", m->b);
return EXIT_SUCCESS;
}
o/p m->b = 3
但我对 *m 的分配有疑问。我试过以下
#include <stdio.h>
int main()
{
int x = (int k = 9;k-2;);
printf("x= %d k = %d",x,k);
}
o/p
one.c:5: error: expected ‘)’ before ‘k’
one.c:5: error: expected expression before ‘;’ token
one.c:6: error: ‘k’ undeclared (first use in this function)
one.c:6: error: (Each undeclared identifier is reported only once
one.c:6: error: for each function it appears in.)
如果这个分配在这里是错误的,那么它是如何在宏容器中工作的。上面两个有什么区别。(我知道一个是宏,另一个是正常声明,但是在宏扩展之后两者看起来都一样)
注意:对不起,这可能很简单,但我无法弄清楚。
kinldy 给我的 dobut 一些解决方案。