tags:

views:

129

answers:

1

Hello

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

+14  A: 
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.eetimes.com/design/embedded/4024941/Learn-a-new-trick-with-the-offsetof--macro

birryree
There are macros for this construct in Windows (`RTL_FIELD_SIZE(type, field)` and Linux (`FIELD_SIZE(t,f)`).
Michael Burr
@Michael: There's no reason to use non-portable system-specific macros when you can write your own portable implementation just as easily.
R..