Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof a struct member [duplicate]

Tags:

c

sizeof

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

like image 506
xyzt Avatar asked Oct 05 '10 14:10

xyzt


1 Answers

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

like image 124
逆さま Avatar answered Oct 19 '22 20:10

逆さま