sizeof(* struct pointer) 是否给你结构的值

Does sizeof(* struct pointer) give you the value of structure

我有这样的结构 sizeof 函数的输出是什么。

struct sample
{
    int a;
    char b;
};

struct sample obj;
struct sample * ptr;

sizeof(*ptr);

我使用 gcc 编译器在 C 中尝试了这段代码,它给出了结构本身的大小。 但我怀疑这是否会在与其他 C 编译器和 C++ 一起尝试时产生相同的结果。

你能帮我解决这个问题吗?

提前致谢。

I tried this piece of code in C using gcc compiler and that gave me the size of the structure itself

理应如此。一元运算符 sizeof 的参数可以是表达式或带括号的类型名称。 C 中的所有表达式都有一个类型。 sizeof 的意思是查看表达式求值的类型,并给出该类型的大小。

因为*ptrstruct sample类型的表达式,结果应该是struct sample的大小。还值得一提的是,通常表达式甚至不需要计算,大小可以静态确定(除非你正在处理 VLA)。

您可以信赖该行为,因为这是 C 标准指定它应该做的事情。它总是给出结构的大小。您不能依赖编译器之间的大小相同,但可以确定 sizeof 的行为。

由于您自己的示例使用指针,因此 "Do I cast the result of malloc?" 中描述了此行为有用的一个地方,您可以在其中提供 malloc 取消引用指针的大小,而不是类型:

struct sample * ptr = malloc(sizeof *ptr);

理由是你不需要重复类型名称两次(在 C++ 中三次,你也需要强制转换),帮助你避免重构时可能出现的细微错误。