指向c中的结构的sizeof指针 [英] sizeof pointer to a structure in c

查看:90
本文介绍了指向c中的结构的sizeof指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是结构声明

struct node
{
  int data;
  struct node *next;
};

当我执行以下行时,ptr2的大小不应该是12个字节(我使用64位计算机)吗?

And when I execute the following line, shouldn't the size of ptr2 be 12 bytes(I use 64-bit machine)?

struct node *ptr;
  struct node ptr2;
  printf("%u\n%u\n",sizeof(ptr),sizeof(ptr2));

输出如下:

kv@kv:~/Desktop$ ./a.out
8
16

推荐答案

,具体取决于您的编译器具有哪些对齐设置.对于对齐关键的struct(例如,用于文件格式解码/编码),请尝试以下操作(如果使用C ++语言,请参见docs如何实现类似功能):

that depends on what align settings you have in your compiler. For align crucial struct's (for example for file-format decoding/encoding purposes) try this (in C++ language if you have different see the docs how to achieve similar functionality):

#pragma pack(1)
struct node
 {
 int data;
 struct node *next;
 };
#pragma pack()

在您的情况下,您似乎已将align设置为8或16个字节.此属性用于对齐数据,以通过更好地解决数学问题和减少缓存丢失而加快内存访问速度.

In your case it looks like you have set align to 8 or 16 bytes. This property is used to align data to speed up memory access by better addressing math and less cache misses ...

  • #pragma pack(x)临时将align属性设置为x个字节
  • #pragma pack()恢复以前的对齐设置.
  • #pragma pack(x) temporarily sets align property to x bytes
  • #pragma pack() restore previous align setting.

您可以将它们看做一键弹出.

You can look at these as a push and pop.

align告诉编译器任何struct/class/union应当对齐的大小,因此它们始终以align属性地址的倍数开始/结束.这对于指针逻辑很重要.例如,如果您将align设置为8或16,并且结构的原始大小为12字节,则编译器将用空白空间填充其余部分,以匹配align大小的倍数(在您的情况下,增加4个字节).这将减少 CACHE 的丢失(如果对齐方式足以容纳您当前的 CPU ).一些编译器也可以利用这一点(如果大小为2的幂),并将指针数学更改为位移.

The align tells compiler on what size should align any struct/class/union so they always start/end at multiple of align property address. This is important for pointer logic. For example if you have align to 8 or 16 and your structure is raw size 12 Bytes the compiler fills the rest with empty space to match multiple of align size (in your case add 4 bytes). This will lead to less CACHE misses (if align is big enough for your current CPU). Some compilers can also take advantage of this (in case of that size is power of 2) and change pointer math to bit shifts.

尝试在IDE中搜索类似以下内容的内容:Project->Options->Compiler->Align

Try to search in your IDE for things like: Project->Options->Compiler->Align

但是,在某些体系结构中,很少有人指出,禁止未经对齐的内存访问(例如SPARC),并且通常会导致崩溃/异常.

这篇关于指向c中的结构的sizeof指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆