sizeof(*ptr) 和 sizeof(struct) 之间的区别
我尝试了以下程序
struct temp{
int ab;
int cd;
};
int main(int argc, char **argv)
{
struct temp *ptr1;
printf("Sizeof(struct temp)= %d\n", sizeof(struct temp));
printf("Sizeof(*ptr1)= %d\n", sizeof(*ptr1));
return 0;
}
输出
Sizeof(struct temp)= 8
Sizeof(*ptr1)= 8
在 Linux 中,我在许多地方观察到了 sizeof(*pointer)
的用法。如果两者相同,为什么使用 sizeof(*pointer)
?
I tried the following program
struct temp{
int ab;
int cd;
};
int main(int argc, char **argv)
{
struct temp *ptr1;
printf("Sizeof(struct temp)= %d\n", sizeof(struct temp));
printf("Sizeof(*ptr1)= %d\n", sizeof(*ptr1));
return 0;
}
Output
Sizeof(struct temp)= 8
Sizeof(*ptr1)= 8
In Linux I have observed at many places the usage of sizeof(*pointer)
. If both are same why is sizeof(*pointer)
used ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常更喜欢
sizeof(*ptr)
因为如果您稍后返回并更改代码,使得ptr
现在具有不同的类型,则不必更新 <代码>大小。实际上,您可以更改ptr
的类型,而不会意识到再往下几行,您正在获取结构的大小。如果您没有多余地指定类型,那么当您稍后需要更改它时,搞砸的可能性就较小。从这个意义上说,它是“可维护性代码”或“防御性代码”之一。
其他人可能有他们的主观原因。通常需要输入的字符较少。 :-)
I generally prefer
sizeof(*ptr)
because if you later go back and change your code such thatptr
now has a different type, you don't have to update thesizeof
. In practice, you could change the type ofptr
without realizing that a few lines further down, you're taking the structure's size. If you're not specifying the type redundantly, there's less chance you'll screw it up if you need to change it later.In this sense it's one of those "code for maintainability" or "code defensively" kind of things.
Others may have their subjective reasons. It's often fewer characters to type. :-)
sizeof
以两种方式之一工作:1) 使用类型,2) 使用表达式。后一种情况与对表达式类型调用sizeof
相同。所以你可以这样写:
两者的意思是一样的。
表达式版本用于声明动态内存指针的实用性在于,您只需拼出类型一次:
如果您稍后选择更改
*pc
的类型,则只需更改代码集中在一处。sizeof
works in one of two ways: 1) with a type, 2) with an expression. The latter case is identical to callingsizeof
on the type of the expression.So you can write this:
Both mean the same thing.
The utility of the expression version for declaring a pointer to dynamic memory is that you only need to spell out the type once:
If you later choose to change the type of
*pc
, you only have to change the code in one single place.