链表中节点的大小
size of a node in linked list
程序:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
struct node* head = NULL;
head = (struct node*)malloc(sizeof(struct node));
cout<<sizeof(struct node)<<"n"<<sizeof(head)<<"n"<<sizeof(int);
return 0;
}
输出:
8
4
4
- 为什么
sizeof(struct node)
与sizeof(head)
不同?malloc不会分配8个字节吗 - 由于
sizeof(head)
是与sizeof(int)
相同,那么next
存储在哪里
head
不是节点,它是指向节点的指针。所以sizeof(head)
会给你一个指针的大小,它与它所指向的东西的大小无关。sizeof(*head)
会给你节点的大小。
原因如下
cout<<sizeof(struct node) // returns the size of struct node 4 bytes for pointer and 4 bytes for int
sizeof(head) // returns the size of pointer 4 bytes
sizeof(int); // returns the size of integer 4 bytes
sizeof
计算表达式的类型的大小。在这种情况下,head
是一个指针。在32位机器上,指针是4个字节,巧合的是整数也是4个字节。
为了在没有实际类型名称的情况下正确地获得head
的大小,sizeof
足够聪明,可以在取消引用对象的情况下计算出来。
// == sizeof(struct node)
sizeof(*head)
相关文章:
- 反向给定链表中的K节点
- 我们可以删除链表中静态内存中的节点吗
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 如何按数字顺序插入链表节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在C++的链表末尾插入一个节点
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 删除链表中的特定节点
- 在 c++ 中,在链表节点上使用括号有什么意义?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 删除链表中的节点 - 分段错误
- 使用函数引用指向节点的指针删除链表中的节点?
- 节点链表中的对象
- 虚拟头节点链表
- C++ 删除类似的节点链表
- c++删除节点链表导致程序崩溃
- 排序节点(链表)c++