16

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

xyzt
  • 1,201
  • 4
  • 18
  • 44

1 Answers1

45
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

Nate C-K
  • 5,744
  • 2
  • 29
  • 45
wkl
  • 77,184
  • 16
  • 165
  • 176
  • 4
    There are macros for this construct in Windows (`RTL_FIELD_SIZE(type, field)` and Linux (`FIELD_SIZE(t,f)`). – Michael Burr Oct 05 '10 at 16:13
  • 4
    @Michael: There's no reason to use non-portable system-specific macros when you can write your own portable implementation just as easily. – R.. GitHub STOP HELPING ICE Oct 05 '10 at 17:00
  • /*Huh, interestingly enough this does not work with abstract structs/classes*/ It does not work on static constants within the same class. – Ramon Zarazua B. Feb 03 '11 at 02:57
  • @RamonZarazuaB. in C++ you should be using `sizeof(A::arr)` – osvein Nov 13 '17 at 16:42
  • This answer seems very portable. I tested on Linux, macos, and FreeBSD (implementation via macro at [commit 5e93355](https://github.com/theimpossibleastronaut/rmw/pull/352/commits/5e93355bcd8a1cd3fd8ff8970b0600c213aaf1ee)). Thanks. – Andy Alt Oct 04 '22 at 15:04