C offsetof 宏是如何工作的? [英] How does the C offsetof macro work?
问题描述
可能重复:
为什么这个 C 代码可以工作?
如何在结构上使用 offsetof()?
我在网上看到过这个 offsetof 宏,但没有说明它的用途.
I read about this offsetof macro on the Internet, but it doesn't explain what it is used for.
#define offsetof(a,b) ((int)(&(((a*)(0))->b)))
它想做什么,使用它有什么好处?
What is it trying to do and what is the advantage of using it?
推荐答案
它没有优势,不应该使用,因为它会调用未定义的行为(并且使用了错误的类型 - int
而不是 <代码>size_t).
It has no advantages and should not be used, since it invokes undefined behavior (and uses the wrong type - int
instead of size_t
).
C 标准在 stddef.h
中定义了一个 offsetof
宏,该宏实际上适用于结构中需要元素偏移量的情况,例如:
The C standard defines an offsetof
macro in stddef.h
which actually works, for cases where you need the offset of an element in a structure, such as:
#include <stddef.h>
struct foo {
int a;
int b;
char *c;
};
struct struct_desc {
const char *name;
int type;
size_t off;
};
static const struct struct_desc foo_desc[] = {
{ "a", INT, offsetof(struct foo, a) },
{ "b", INT, offsetof(struct foo, b) },
{ "c", CHARPTR, offsetof(struct foo, c) },
};
这将让您以编程方式按名称填充 struct foo
的字段,例如读取 JSON 文件时.
which would let you programmatically fill the fields of a struct foo
by name, e.g. when reading a JSON file.
这篇关于C offsetof 宏是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!