Hello All将链表的节点称为
struct node
{
int data;
struct node* next;
};
考虑使用4个字节的int。指针下一个的大小是什么?
我还有以下内容,
void * ptr;
printf("%d",sizeof(ptr));
指针大小为8个字节。
我将sizeof(struct node)改为12,给定struct节点中 next 指针大小的大小是多少12.请帮我理解。 提前谢谢。
答案 0 :(得分:1)
指针的大小是存储地址所需的字节数:
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.3.1/css/bulma.css" rel="stylesheet"/>
<div class="columns">
<div class="column box">
1
</div>
<div class="column box">
2
</div>
</div>
上述每一项都应在具有64位地址的计算机上返回printf("%zu",sizeof(ptr));
printf("%zu",sizeof(struct node *));
printf("%zu",sizeof &abc);
,在具有32位地址的计算机上返回8
。
可以通过取消引用指针来获取节点的大小:
4
如上所述,上面应该在具有64位地址的计算机上返回struct node abc;
void *ptr = &abc;
printf("%zu",sizeof(*((struct node *)ptr)));
。
答案 1 :(得分:1)
在典型系统中,指针的大小与其指向的数据大小无关。在32位系统上,指针是32位(4字节),在64位系统上,指针是64位(8字节)。
您的结构大概是12个字节,大概是因为它包含一个4字节int
和一个8字节指针。但是,这是特定于平台的,可能会有所不同。许多系统要求值为aligned到其大小的整数倍 - 也就是说,64位指针必须从一个8字节倍数的地址开始。编译器将在结构成员之间插入填充以满足对齐要求。
在我的x86-64 Linux系统上,结构的大小为16个字节:int
为4个字节,4个字节的填充为8个字节的边界,8个字节为指针。< / p>
答案 2 :(得分:1)
下一个指针的大小是什么?
尺寸为sizeof(struct node*)
不应根据特定结果编写代码。
结果可能是4或8,或1或16或其他。
编写便携式 C代码依赖于不知道答案,而不是像1到64这样的理智范围。
OP没有提到需要知道sizeof(ptr)
大小值的原因,但答案只是指针的大小是sizeof(ptr)
。代码应使用sizeof(ptr)
而不是像4或8这样的幻数。
要打印指针的大小,请使用
some_type* ptr;
// printf("%d",sizeof(ptr));
printf("%zu",sizeof(ptr));
z 指定以下d,i,o,u,x或X转换规范适用于
size_t
C11dr§7.21.6.17
int *
,const int *
,void *
,int (*)()
等指针的大小可能会有所不同。可移植代码并不假设所有指向各种类型的指针都具有相同的大小。
答案 3 :(得分:0)
sizeof(pointer)
都是常数。既然你做了:
sizeof(ptr)
并得到8 bytes
我会猜测你是在64位系统上。这向我表明您的sizeof(struct node)
将是12个字节,因为您有以下内容:
struct node {
int data; // 4 Bytes (32 bit, a common size for `int`s)
struct node* next; // 8 Bytes, as are all pointers on your system
}; // total size of 12 bytes.