gpt4 book ai didi

container_of 宏不适用于 char* 或数组成员

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:56 24 4
gpt4 key购买 nike

我正在阅读 John Madieu 的 Linux Device Drivers Development,其中一段说

The container_of macro won't work for char * or array members. It
means the first member of container_of must not be a pointer to
another pointer to char nor to array in the structure.

这是 container_of 的定义:

#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr);
(type *)( (char *)__mptr - offsetof(type,member) );})

如果我有

struct person {
int age;
int salary;
char *name;
} me;

我有 char ** my_name = &(me.name);,为什么我不能执行以下操作:

struct person * me = container_of(my_name,struct person,name);

最佳答案

这是由于 ISO C 关于指针初始化的规则,在这种情况下会破坏 __mptr 的初始化。

这是一个简单的例子:

int main()
{
char ar[5] = {0};
const char (*ptr)[5] = &ar;
}

// warning: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]

( live demo )

a prior SO question 上有关于这个问题的讨论。 .注意 C++ has no such limitation ; const 可以自由添加。

A kernel dev discussion建议将 __mptr 替换为另一种在 container_of 中执行类型检查的方法,因此您可能会发现这已经不再影响您。

关于container_of 宏不适用于 char* 或数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008138/

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