链表中节点的大小

size of a node in linked list

本文关键字:节点 链表      更新时间:2023-10-16

程序:

#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
  1. 为什么sizeof(struct node)sizeof(head)不同?malloc不会分配8个字节吗
  2. 由于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)