C++ – Getting the size in bytes or in chars of a member of a struct or union in C/C++


Let's say that I want to get the size in bytes or in chars for the name field from:

struct record
    int id;
    TCHAR name [50];

sizeof(record.name) does not work.

Best Solution

The solution for this is not so pretty as you may think:

size_in_byte = sizeof(((struct record *) 0)->name)

size_in_chars = _countof(((struct record *) 0)->name)

If you want to use the second one on other platforms than Windows try:

#define _countof(array) (sizeof(array)/sizeof(array[0]))