C++ 链表中节点的大小
节目:C++ 链表中节点的大小,c++,malloc,sizeof,C++,Malloc,Sizeof,节目: #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<<si
#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
coutsizeof
计算表达式类型的大小。在本例中,head
是一个指针。在32位机器上,指针是4字节,同时整数也是4字节
要正确获取head
的大小,而不使用实际的类型名称,sizeof
足够智能,可以在取消引用对象时计算出来
// == sizeof(struct node)
sizeof(*head)
为什么不使用C++来代替C++中的C代码呢?(换句话说:与malloc相比,更喜欢new
,但尽可能使用智能指针、自动存储和容器类)。另外,struct node{}
使节点
成为一个类型名,因此在使用该类型时不需要重复结构
。c++|链表中节点的大小
sizeof()是一个编译时值,因此您的问题与malloc
或链表完全无关。为什么sizeof(head)是4个字节,为什么不是其他的东西?@g4ur4v:因为在您的实现中存储对象地址需要多少字节。@g4ur4v请看这里:正如Benjamin指出的,大小可以是“其他的东西”。为什么sizeof(head)是4字节,为什么不是其他的东西?指针的大小可以是4字节或8字节,具体取决于体系结构。