自己的offsetof实现会产生警告 [英] Own offsetof implementation produces warning
问题描述
我写了一小段代码来了解offsetof宏在后台如何工作.代码如下:
I wrote a small piece of code to understand how the offsetof macro works in the background. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Getting the offset of a variable inside a struct */
typedef struct {
int a;
char b[23];
float c;
} MyStructType;
unsigned offset = (unsigned)(&((MyStructType * )NULL)->c);
printf("offset = %u\n", offset);
return 0;
}
但是,如果我运行它,则会收到警告消息:
However, if I run it I get a warning message:
警告:从指针强制转换为不同大小的整数[-Wpointer-to-int-cast]
WARNING: cast from pointer to integer of different size [-Wpointer-to-int-cast]
但是,如果我查看c中原始的offsetof宏,代码将如下所示:
However, if I look at the original offsetof macro in c, the code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
int main(void)
{
/* Getting the offset of a variable inside a struct */
typedef struct {
int a;
char b[23];
float c;
} MyStructType;
unsigned offset = offsetof(MyStructType, c);
printf("offset = %u\n", offset);
return 0;
}
那么当我强制转换为unsigned时,为什么会收到警告?它似乎是offsetof宏的类型.这让我感到困惑.
So why do I get the warning as I cast to unsigned ? It appears to be the type for the offsetof macro. This is puzzling me.
推荐答案
正如mch所评论的, unsigned
不是正确的类型.在几乎所有实际系统中,它都是32位的. offsetof
宏应该产生类型为 size_t
的结果,这是您应该"投射到的结果.我认为您对将结果存储到 unsigned
类型的对象中的代码感到困惑;只要确定值很小就可以,但这并不表示 offsetof(MyStructType,c);
的类型是 unsigned
.C允许您将较大的整数类型静默分配给较小的整数类型.
As mch commented, unsigned
is not the right type; it's 32-bit on pretty much all real-world systems. The offsetof
macro is supposed to produce a result of type size_t
, which is what you "should" be casting to here. I think you're confused by the code you found storing the result into an object of type unsigned
; that's okay as long as they're sure the value is small, but it doesn't mean the type of the expression offsetof(MyStructType, c);
was unsigned
. C allows you to silently assign a larger integer type into a smaller one.
但是,无论您做什么,这不是 offsetof
的有效实现,并且具有未定义的行为(通过应用->
指向无效的指针).没有UB的有效 offsetof
的方法是 #include< stddef.h>
.
However, no matter what you do, this is not a valid implementation of offsetof
and has undefined behavior (via applying ->
to an invalid pointer). The way you get a working offsetof
without UB is #include <stddef.h>
.
这篇关于自己的offsetof实现会产生警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!