【发布时间】: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
- 为什么
sizeof(struct node)与sizeof(head)不同? malloc 不会分配 8 个字节吗? - 因为
sizeof(head)是 和sizeof(int)一样,那么next存储在哪里?
【问题讨论】:
-
与其用 C++ 编写 C 代码,为什么不使用 C++? (换句话说:更喜欢
new而不是malloc,但尽可能使用智能指针、自动存储和容器类)。此外,struct node { };使node成为类型名,因此在使用类型时无需重复struct。 -
c++ | size of a node in linked listsizeof() 是编译时值,因此您的问题与malloc或链表完全无关。