本文介绍了在c ++中声明变量和动态分配内存到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,当我只是声明一个变量,如:

I'm a bit confused about the difference between when I just declare a variable such as:

int n;

并使用new将内存动态分配给变量,例如:

and dynamically assigning memory to a variable using "new" such as:

int m = new int;

我注意到只是从一个简单的链表项目,当我插入一个新的值节点对象的形式,我必须动态创建一个新的节点对象,并附加所需的值到它,然后链接到我的列表的其余部分。但在同一个函数中,我可以只定义另一个节点对象,ex。 NodeType * N。并使用此指针遍历我的列表。
我的问题是..当我们只是声明一个变量,内存不会立即分配..或有什么区别?

I noticed just from working on a simple linked list project that when I'm inserting a new value in the form of an node object, I have to dynamically create a new node object and append the desired value to it and then link it to the rest of my list. However.. in the same function, I could just define another node object, ex. NodeType *N. and traverse my list using this pointer.My question is.. when we just declare a variable, does memory not get assigned right away.. or what's the difference?

谢谢! p>

Thank you!

推荐答案

如有可能,首选自动存储分配的变量:

Prefer automatic storage allocated variables when possible:

int n;

int* m = new int; // note pointer

动态分配的首要原因是链表定义的方式。也就是说每个节点包含指向下一个节点的指针(可能)。因为节点必须存在,超出它们创建的点,所以它们是动态分配的。

The reason dynamic allocation is prefered in your case is the way the linked list is defined. I.e. each node contains a pointer to a next node (probably). Because the nodes must exist beyond the point where they are created, they are dynamically allocated.

是的,你可以这样做。但请注意,这只是一个指针声明。

Yes, you could do that. But note that this is just a pointer declaration. You have to assign it to something meaningful to actually use it.

实际上,这两种情况都是定义,而不仅仅是声明。

Actually, both cases are definitions, not just declarations.

int n;

创建一个未初始化的 int 存储;

creates an un-initialized int with automatic storage;

int* n;

创建指向 int 的指针。它是悬空的,它不指向有效的内存位置。

creates a pointer to an int. It's dangling, it doesn't point to a valid memory location.

int* n = new int;

创建一个指针并将其初始化到包含未初始化 int的有效内存位置

creates a pointer and initializes it to a valid memory location containing an uninitialized int.

int* n = new int();

创建一个指针并将其初始化到一个有效的内存位置,包含一个值初始化的 int (即 0 )。

creates a pointer and initializes it to a valid memory location containing a value-initialized int (i.e. 0).

这篇关于在c ++中声明变量和动态分配内存到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:06
查看更多