什么是通用的C / C ++宏来确定结构成员的大小? [英] What is a common C/C++ macro to determine the size of a structure member?

查看:104
本文介绍了什么是通用的C / C ++宏来确定结构成员的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++中,如何确定结构的成员变量的大小,而无需定义该结构类型的虚拟变量?这里有一个例子,说明如何做错了,但显示的意图:

In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:

typedef struct myStruct {
  int x[10];
  int y;
} myStruct_t;

const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x);  // error

为了参考,这应该是如何找到'x'定义一个虚拟变量:

For reference, this should be how to find the size of 'x' if you first define a dummy variable:

myStruct_t dummyStructVar;

const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);

但是,我希望避免创建一个虚拟变量, X'。我认为有一个聪明的方式重写0作为一个myStruct_t帮助找到成员变量'x'的大小,但它已经足够长,我已经忘记了细节,似乎不能得到一个好的谷歌搜索这个。你知道吗?

However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?

谢谢!

推荐答案

是标签说的),你的虚拟变量代码可以替换为:

In C++ (which is what the tags say), your "dummy variable" code can be replaced with:

sizeof myStruct_t().x;

不会创建myStruct_t对象:编译器只能处理sizeof操作数的静态类型,

No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.

这在C中工作,在C ++中更好,因为它也适用于没有可访问的无参数构造函数的类:

This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:

sizeof ((myStruct_t *)0)->x

这篇关于什么是通用的C / C ++宏来确定结构成员的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆