gpt4 book ai didi

c - Linux内核container_of宏示例编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:01:07 30 4
gpt4 key购买 nike

谁能告诉我这段代码有什么问题:

#include <stdio.h>
#include <stdlib.h>

#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) );})
typedef struct _elem {
int a;
float b;
double c;
} elem;

int main(int argc, char **argv)
{
elem *my_elem = (elem *)malloc(sizeof *elem);

my_elem->a = 1;
my_elem->b = 2;
my_elem->c = 3;
elem *new_elem_a = container_of(&(my_elem->a), struct _elem, int);
fprintf(stdout, "container_of(&(my_elem->a), struct _elem, int) = %p", new_elem_a);

return 0;
}

当我编译时我得到了这个错误:

evariste@UnixServer:~$ gcc -Wall container_of_test.c -o container_of_test
container_of_test.c: In function ‘main’:
container_of_test.c:16:51: erreur: expected expression before ‘elem’
container_of_test.c:21:32: erreur: expected identifier before ‘int’
container_of_test.c:21:32: erreur: expected identifier before ‘int’

感谢您的帮助。

最佳答案

这里有2个错误

  1. container_of 宏期望最后一个参数是成员名称。所以应该是

    elem *new_elem_a = container_of(&(my_elem->a), struct _elem, a);

  2. elem *my_elem = (elem *)malloc(sizeof *elem)

    sizeof操作数错误,应该是

    elem *my_elem = (elem *)malloc(sizeof *my_elem)

关于c - Linux内核container_of宏示例编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11705514/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com