Getting size in bytes or in characters of a member of a structure or union in C / C ++?

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

struct record
{
    int id;
    TCHAR name [50];
};

sizeof(record.name) does not work.

+3
source share
6 answers

The solution for this is not as pretty as you 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 platforms other than Windows, follow these steps:

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

+8
source

If you first create an instance, it will work.

record r;
sizeof(r.name);
+7
source

++:

#include <iostream>
using namespace std;;

struct record
{
    int id;
    char name [50];
};

int main() {
    cout << sizeof( record::name) << endl;
}

:. , ++ 0x, , , V++. , - ++-, , sizeof ++ 03? , . , . ++: -)

+5

record - , record.name - . - . - C:

sizeof ((struct record*)0)->name;

- ( -) struct record, name sizeof. , sizeof , .

+2

, , , .

+1
struct record
{
    static const int kMaxNameChars=50;
    int id;
    TCHAR name [kMaxNameChars];
};


sizeof(TCHAR)*record::kMaxNameChars //"sizeof(record.name)"
//record::kMaxNameChars sufficient for many purposes.

, IMO, , .

(edit: you may need a C macro if the compiler is upset about the length of the array of variables. If you do, consider defining a static int constant for the macro value anyway!)

+1
source

Source: https://habr.com/ru/post/1725301/


All Articles