简体   繁体   English

在C / 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: 假设我想从以下位置获取name字段的字节大小或字符:

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

sizeof(record.name) does not work. sizeof(record.name)不起作用。

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: 如果要在除Windows之外的其他平台上使用第二个,请尝试:

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

If you create an instance first, it will work. 如果您先创建一个实例,它将起作用。

record r;
sizeof(r.name);

In C++: 在C ++中:

#include <iostream>
using namespace std;;

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

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

Edit: A couple of people have pointed out that this is C++0x code, so I guess I must retract my unkind comment regarding VC++. 编辑:有几个人指出这是C ++ 0x代码,所以我想我必须撤回我对VC ++的不友好评论。 This is not a programming construct I have ever used in my own C++ code, but I have to wonder why sizeof would not work this way in C++03? 这不是我在自己的C ++代码中使用过的编程结构,但我不得不想知道为什么sizeof在C ++ 03中不能这样工作? You hand it a name and it gives you the size. 你给它起一个名字,它给你的大小。 I'd have thought it would take some effort for it not to work. 我以为它不需要工作需要一些努力。 But such is the wonder of the C++ Standard :-) 但这就是C ++标准的奇迹:-)

record is the name of a type, but record.name is not. record是类型的名称,但record.name不是。 You somehow have to access name through an instance of the struct. 你不知何故必须通过struct的实例访问name。 Sorin's answer is the usual C solution: Sorin的答案是通常的C解决方案:

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

This creates a pseudo-pointer to an instance (or pointer to a pseudo-instance) of struct record , then access the name member, and pass that expression to sizeof . 这将创建一个指向struct record的实例(或指向伪实例的指针)的伪指针,然后访问name成员,并将该表达式传递给sizeof It works because sizeof doesn't attempt to evaluate the pointer expression, it just uses it to compute the size. 它的工作原理是因为sizeof不会尝试计算指针表达式,它只是用它来计算大小。

你可能想读这个 ,因为它讨论了同样的问题并提供了这个线程中提到的所有选项,还有更多。

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.

Portable, perfectly safe and IMO being explicit about raw array length is good practice. 便携,完全安全和IMO明确的原始阵列长度是很好的做法。

(edit: you might have to macro it in C, if the compiler gets upset about variable array lengths. if you do, consider defining a static const int to the value of the macro anyway!) (编辑:如果编译器对变量数组长度感到不安,你可能不得不在C中使用它。如果你这样做,考虑将静态const int定义为宏的值!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM