Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 链表中节点的大小_C++_Malloc_Sizeof - Fatal编程技术网

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
    

    cout
    sizeof
    计算表达式类型的大小。在本例中,
    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字节,具体取决于体系结构。