【发布时间】:2011-08-29 17:18:27
【问题描述】:
在以下程序中:
// illustration of linked list
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
struct node* buildList();
int main() {
struct node* head = buildList();
cout << head->data;
}
struct node* buildList() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = new node; // builds up a pointer structure on heap
second = new node;
third = new node;
head->data = 1;
head->next = second;
head->data = 2;
second->next = third;
head->data = 3;
third->next = NULL;
return head;
}
我不知道new 操作员在这里的工作。他们执行什么任务? (我读到它在堆上分配空间。但我不知道这是什么意思)如果我删除这些语句,则没有输出并且程序崩溃。这是为什么呢?
【问题讨论】:
-
1) 这是一个“新的表达式”,而不是一个运算符。 2) 扔掉这本书——
new创建一个具有动态存储和生命周期的新对象,这才是最重要的。
标签: c++ list visual-c++ linked-list new-operator