链表中节点的大小

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
  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 计算表达式 type 的大小。在这种情况下 head 是一个指针。在 32 位机器上指针是 4 个字节,巧合的是整数也是 4 个字节。

要在没有实际类型名称的情况下正确获取 head 的大小,sizeof 足够聪明,可以在取消引用对象时弄清楚。

// == sizeof(struct node)
sizeof(*head)