获取 C/C 中结构或联合成员的大小(以字节为单位或以字符为单位)?
假设我想从以下位置获取名称字段的大小(以字节或字符为单位):
struct record
{
int id;
TCHAR name [50];
};
sizeof(record.name)
不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这个问题的解决方案并不像您想象的那么漂亮:
size_in_byte = sizeof(((struct record *) 0)->name)
size_in_chars = _countof(((struct record *) 0)->name)
如果您想在 Windows 以外的其他平台上使用第二个,请尝试:
#define _countof(array) (sizeof(array)/sizeof(array[0]))< /代码>
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]))
如果您先创建一个实例,它就会起作用。
If you create an instance first, it will work.
在 C++ 中:
编辑: 有几个人指出这是 C++0x 代码,所以我想我必须收回我对 VC++ 的不友善评论。这不是我在自己的 C++ 代码中使用过的编程结构,但我想知道为什么 sizeof 在 C++03 中不能以这种方式工作?你给它一个名字,它就会给你尺寸。我原以为需要付出一些努力才不会起作用。但这就是 C++ 标准的奇妙之处:-)
In C++:
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++. 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? 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 :-)
record
是类型的名称,但record.name
不是。您必须以某种方式通过结构的实例访问名称。 Sorin 的答案是通常的 C 解决方案:这会创建一个指向
struct record
实例(或指向伪实例的指针)的伪指针,然后访问name
成员,并将该表达式传递给sizeof
。它之所以有效,是因为sizeof
不会尝试计算指针表达式,它只是使用它来计算大小。record
is the name of a type, butrecord.name
is not. You somehow have to access name through an instance of the struct. Sorin's answer is the usual C solution:This creates a pseudo-pointer to an instance (or pointer to a pseudo-instance) of
struct record
, then access thename
member, and pass that expression tosizeof
. It works becausesizeof
doesn't attempt to evaluate the pointer expression, it just uses it to compute the size.您可能想阅读这个,因为它讨论了完全相同的问题并提供了该线程中提到的所有选项,以及更多选项。
You might wanna read this, as it discusses the very same issue and provides all the options mentioned in this thread, and a little more.
便携、完全安全并且在我看来明确原始数组长度是很好的做法。
(编辑:如果编译器对可变数组长度感到不安,你可能必须在 C 中对其进行宏定义。如果这样做,请考虑将 static const int 定义为宏的值!)
Portable, perfectly safe and IMO being explicit about raw array length is good practice.
(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!)