使用 sizeof 访问结构体成员
我有这段代码,我不明白为什么它不能编译:
typedef struct
{
uint32_t serial_number;
uint32_t ieee_address[6];
} FACTORY_CONFIG;
...
// Unlock flash (only the portion we write on)
error = FLASHD_Unlock ( writeaddress, writeaddress + sizeof ( FACTORY_CONFIG.serial_number ), 0, 0 );
当我运行它时,我收到此错误:
错误[Pe018]:需要一个“)”
当我更改
FACTORY_CONFIG.serial_number
至
FACTORY_CONFIG
,它编译并且一切正常。我不确定,我可以检查结构内类型的大小吗?
I've got this code, which I don't understand why it doesn't compile:
typedef struct
{
uint32_t serial_number;
uint32_t ieee_address[6];
} FACTORY_CONFIG;
...
// Unlock flash (only the portion we write on)
error = FLASHD_Unlock ( writeaddress, writeaddress + sizeof ( FACTORY_CONFIG.serial_number ), 0, 0 );
When I run it, I get this error:
Error[Pe018]: expected a ")"
When I change the
FACTORY_CONFIG.serial_number
to
FACTORY_CONFIG
, it compiles and everything works. I'm not sure, can I check the size of a type inside a structure ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能像这样访问 C 中类型的成员。但是,您可以从实际对象中获取
sizeof
。由于 sizeof 是一个编译时构造,这些对象甚至不必是有效的。因此,以下内容将起作用:如果您经常使用它,或者只是为了可读性,您可以用它制作一个宏。
You can't just access members of types in C like that. You can, however, take
sizeof
from actual objects. And sincesizeof
is a compile-time construct, these objects don't even have to be valid. So the following will work:If you use this a lot, or just for readability, you could make a macro out of it.
您似乎想要的是将您的
writeaddress
解释为好像它指向struct
的对象,然后访问ieee_address
的地址> 会员。这些事情在 C 中的完成方式就是
这样。
您使用的方法非常危险,因为您不知道编译器将如何在内存中布局
struct
。如果必须的话,可以使用offsetof
宏来获取字段的确切位置。顺便说一句,类型别名全部大写不符合常见的编码风格,也不符合每个人的习惯。通常所有大写名称都是为宏保留的。
What you seem to want, ist to interpret your
writeaddress
as if it were pointing to an object of yourstruct
and then access the address of theieee_address
member.The way such things are meant to be done in C is
that's it.
The method you were using is very dangerous because you don't know how your compiler will layout the
struct
in memory. If you have to, there is theoffsetof
macro to get the exact postion of a field.BTW, having type alias in all caps is against common coding style and against everybody's habits. Usually all caps names are reserved for macros.
您需要首先创建该对象。您正在创建的结构只是一种类型。
这样做:
You need to create the object first. The struct you are creating is only a type.
Do like this: