sizeof a struct member [duplicate]

扶醉桌前 提交于 2019-12-05 12:59:13

问题


How can I get the size of a member in a struct in C?

struct A
{
        char arr[64];
};

i need something like that:

sizeof(A::arr)

thanks


回答1:


sizeof(((struct A*)0)->arr);

Briefly, cast a null pointer to a type of struct A*, but since the operand of sizeof is not evaluated, this is legal and allows you to get size of struct members without creating an instance of the struct.

Basically, we are pretending that an instance of it exists at address 0 and can be used for offset and sizeof determination.

To further elaborate, read this article:

http://www.embedded.com/design/prototyping-and-development/4024941/Learn-a-new-trick-with-the-offsetof--macro



来源:https://stackoverflow.com/questions/3864583/sizeof-a-struct-member

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!