【问题标题】:size of a node in linked list链表中节点的大小
【发布时间】:2015-05-27 19:41:11
【问题描述】:

计划:

#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存储在哪里?

【问题讨论】:

  • 与其用 C++ 编写 C 代码,为什么不使用 C++? (换句话说:更喜欢new 而不是malloc,但尽可能使用智能指针、自动存储和容器类)。此外,struct node { }; 使 node 成为类型名,因此在使用类型时无需重复 struct
  • c++ | size of a node in linked list sizeof() 是编译时值,因此您的问题与malloc 或链表完全无关。

标签: c++ malloc sizeof


【解决方案1】:

head 不是节点,它是指向节点的指针。所以sizeof(head) 给你一个指针的大小,它与它指向的东西的大小无关。 sizeof(*head) 会给你一个节点的大小。

【讨论】:

  • 为什么 sizeof(head) 是 4 个字节,为什么不是别的呢?
  • @g4ur4v:因为在你的实现中存储一个对象的地址需要多少字节。
  • @g4ur4v 见这里:coliru.stacked-crooked.com/a/7c2bdc2772127d2f 正如本杰明所指出的,尺寸可以是“别的东西”。
【解决方案2】:

原因如下

 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) 是 4 个字节,为什么不是别的呢?
  • 指针的大小可以是 4 字节或 8 字节,具体取决于架构。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 2019-07-19
    • 2021-12-16
    • 2019-10-03
    • 2015-03-17
    • 1970-01-01
    • 2019-11-06
    • 2011-05-28
    相关资源
    最近更新 更多