创建链表时使用 new 运算符

发布于 2024-12-02 02:59:10 字数 804 浏览 2 评论 0原文

在以下程序中:

// 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 运算符在这里的工作。他们执行什么任务? (我读到它在堆上分配空间。但我不知道这是什么意思)如果我删除这些语句,则没有输出并且程序崩溃。这是为什么 ?

In the following program :

// 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;
}

i am unaware of the new operator's work here. What task they perform ? (I read that it allocates space on heap.But i don't know what does it mean) If i remove these statements there is no output and the program crashes. Why is that ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风情万种。 2024-12-09 02:59:10

head、第二和第三变量是指向内存中节点的指针。但是,在使用它们之前,它们必须指向内存中的有效节点。这就是 new 运算符的用武之地。堆只是分配给程序以动态创建对象的内存区域(与堆栈相反。请参阅 此处了解差异)。

The head, second, and third variables are pointers to nodes in memory. But, before you can use them, they must be pointing at a valid node in memory. This is where the new operator comes in. The heap is just an area of memory that has been allocated to your program to dynamically create objects (as opposed to the stack. See here for the difference).

2024-12-09 02:59:10

* 编辑*

我只是想在回答之前添加:

简单来说,堆栈是程序当前正在运行的地方,并且有些是临时的。我的意思是你的 main() 函数可能会调用另一个函数。该函数将有自己的作用域({} 之间的区域)、自己的局部变量、空间等。它可能会依次调用另一个函数。这些函数一直被放在“堆栈上”。一旦函数返回,它将被从堆栈中取出,并且您将返回到您开始的下一级函数中的点。就好像您在当前笔记本上放了一张纸,记了一些笔记,然后将其移开以返回到原始页面。 “堆栈变量”是您在函数中以正常方式创建的变量,它们在离开作用域时死亡/破坏。

堆变量是静态/全局变量,或者使用“new、malloc 等”创建的变量。这些变量是永久性的,并且将持续/存在,直到您显式调用它们的删除为止。它们将在创建它们的范围之外生存,如果您不跟踪它们,它们的资源将无法释放,并且您将出现内存/资源泄漏。

普通帖子

这些行:

struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

都是创建指针,节点后面的 * 表明它是指向节点的指针。这些指针被初始化为 NULL 或 0。指针只是一个内存地址/位置,其中还没有节点对象。因此,

node* ptr = NULL;  //creates pointer to a node object, but no node itself.
node  obj;         //creates an actual node object on the stack.

指针可用于通过使用 & 获取其地址来指向基于堆栈的对象。像这样的运算符:

node obj;  //Real object.
node* ptr = &obj;  //ptr points to the "address of" obj.

在您的情况下,节点指针不会指向任何内容,直到您使用“new”创建它。之后,指针指向“动态分配”的内存,该内存将永远存在,直到您对其调用“删除”为止。这样做的好处是内存可以在创建它的函数之外保留。所以:

void myFunction()
{
    node obj;
}  //obj dies here.

void myOtherFunction()
{
    node* ptr = new obj;
} //the "node" created by new will survive after this.

我可以继续说下去,但是你需要阅读一本 C++ 书籍并理解这一点 - 指针是你需要完全学习的语言的一个关键方面。

* EDIT*

I just thought I'd add in before my answer:

The stack is, in simple terms, the place where your program is currently working and is somewhat temporary. What I mean by that is your main() function may call another function. That function will have its own scope (the area between the {}), its own local variables, space etc. It may in turn call another function. These functions keep being put "on the stack". Once a function returns, it will be taken off the stack and you will return to the point in the next-level-up function in which you started. It's as if you put a piece of paper on top of your current notebook, took some notes, then removed it to get back to your original page. "Stack Variables" are those that you create in normal ways within a function, and they die/destruct upon leaving scope.

Heap variables are those that are static/global, or those created using "new, malloc, etc." These variables are permanent and will persist/exist until you call delete on them explicitly. They will survive outside the scope in which they were created, and if you don't keep track of them their resources will be un-freeable and you will have a memory/resource leak.

Normal Post

The lines:

struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

are all creating pointers the * after node states that it is a pointer to a node. These pointers are initialized to NULL, or 0. A pointer is just a memory address/location, it has no node object in it yet. So,

node* ptr = NULL;  //creates pointer to a node object, but no node itself.
node  obj;         //creates an actual node object on the stack.

Pointers can be used to point to a stack based object by taking its address with the & operator like this:

node obj;  //Real object.
node* ptr = &obj;  //ptr points to the "address of" obj.

In your case, a node pointer doesn't point to anything until you create it with "new". After that, the pointer points to "dynamically allocated" memory which will persist forever and ever until you call "delete" on it. The perk of this is the memory can persist outside the function in which it is created. So:

void myFunction()
{
    node obj;
}  //obj dies here.

void myOtherFunction()
{
    node* ptr = new obj;
} //the "node" created by new will survive after this.

I could go on, but you need to read a c++ book and understand this - pointers are a key aspect of the language you need to learn completely.

萌能量女王 2024-12-09 02:59:10

结构节点* head = NULL; ->创建一个指针(由于赋值而指向 null)

head = new node; ->将内存分配给节点的大小并将 head 指向该内存的开头,

因此如果您的指针为 NULL 并且您从未告诉它指向节点(或任何东西),那么对该指针或对该指针的任何操作都将失败

struct node* head = NULL; -> creates a pointer (points to null because of the assignment)

head = new node; -> allocates memory to the size of a node and points head to the start of that memory

so if ur pointer is NULL and u never tell it to point to a node (or anything) then any operations on that pointer or with that pointer will fail

眼眸印温柔 2024-12-09 02:59:10

new 构造该类型的一个新对象。

在本例中,您正在构建一个新节点。然而,在某些代码中您不需要这样做,您可以简单地使用对象。即节点头;头数据 = 1; head.next = 废话。

使用 new 的原因是为了简单地创建该类型的“新”对象。通常用于动态事物,在这种情况下它看起来像某种链接列表,所以是的,你需要 new。但对于每一个新数据,您都需要在完成后删除数据
否则就会出现内存泄漏,在这种情况下,列表越大,并且您不再解构不再需要的东西,浪费的内存就越多。

但是,您根本不需要使用任何此类代码。相反,标准库中已经有一个容器提供这种类型的支持,以及额外的附加功能。

#include <list> 
// and use
std::list<type> data;

您可以轻松地在此列表中插入和删除数据,它将为您处理分配和释放;这意味着您永远不需要使用 new 或 delete,并且您可以放心地假设内存将为您管理,并且不会出现内存泄漏。

new constructs a new object of that type.

In this case you're constructing a new node. However in some code you don't need to do that, instead you could simply use objects. i.e node head; head.data = 1; head.next = blah.

The reason new is used is to simply create a "new" object of that type. Usually used for a dynamic thing, in this case it looks like a linked list of some sort, so yes you would require new. But with every new, you need to delete the data when you're finished with
otherwise you'll have a memory leak, in which case the larger the list gets, and you don't deconstruct things that are not required anymore, the more memory it's going to waste.

However, you should not need to use any of this code at all. Rather there is already a container in the standard library that offers this type of support, plus extras on the side.

#include <list> 
// and use
std::list<type> data;

you can easily insert and delete data in this list and it will handle the allocations and deallocations for you; which means you don't ever need to use new or delete and you can safely assume that the memory will be managed for you and there will be no memory leaks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文