如何的C offsetof宏的工作? [英] How does the C offsetof macro work?

查看:173
本文介绍了如何的C offsetof宏的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:

  为什么这款C code的工作?

  你怎么在一个结构用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标准定义的 offsetof STDDEF.H 哪些实际工作,在您需要的情况下,在一个结构的元件的偏移,如:

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:

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) },
};

这将让你填写编程的结构美孚按名称,例如田野阅读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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆