使用 sizeof 访问结构体成员

发布于 2024-12-20 21:16:00 字数 562 浏览 3 评论 0原文

我有这段代码,我不明白为什么它不能编译:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独岁月 2024-12-27 21:16:00

你不能像这样访问 C 中类型的成员。但是,您可以从实际对象中获取 sizeof。由于 sizeof 是一个编译时构造,这些对象甚至不必是有效的。因此,以下内容将起作用:

sizeof(((FACTORY_CONFIG *)0)->serial_number)

如果您经常使用它,或者只是为了可读性,您可以用它制作一个宏。

You can't just access members of types in C like that. You can, however, take sizeof from actual objects. And since sizeof is a compile-time construct, these objects don't even have to be valid. So the following will work:

sizeof(((FACTORY_CONFIG *)0)->serial_number)

If you use this a lot, or just for readability, you could make a macro out of it.

誰ツ都不明白 2024-12-27 21:16:00

您似乎想要的是将您的 writeaddress 解释为好像它指向 struct 的对象,然后访问 ieee_address 的地址> 会员。

这些事情在 C 中的完成方式就是

((FACTORY_CONFIG*)writeaddress)->ieee_address

这样。

您使用的方法非常危险,因为您不知道编译器将如何在内存中布局struct。如果必须的话,可以使用 offsetof 宏来获取字段的确切位置。

顺便说一句,类型别名全部大写不符合常见的编码风格,也不符合每个人的习惯。通常所有大写名称都是为宏保留的。

What you seem to want, ist to interpret your writeaddress as if it were pointing to an object of your struct and then access the address of the ieee_address member.

The way such things are meant to be done in C is

((FACTORY_CONFIG*)writeaddress)->ieee_address

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 the offsetof 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.

携余温的黄昏 2024-12-27 21:16:00

您需要首先创建该对象。您正在创建的结构只是一种类型。
这样做:

sizeof (((FACTORY_CONFIG *)0)->serial_number)

You need to create the object first. The struct you are creating is only a type.
Do like this:

sizeof (((FACTORY_CONFIG *)0)->serial_number)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文