c++什么是“指针=新类型”与“指针=新类型[]”相反?
在许多教程中,关于动态内存的第一个代码示例都是这样开始的:
int * pointer;
pointer = new int; // version 1
//OR
pointer = new int [20]; // version 2
他们总是继续解释第二个版本是如何工作的,但完全避免谈论第一个版本。
我想知道的是,pointer = new int
创建了什么?我能用它做什么?这是什么意思?每个教程都会完全避免谈论第一个版本。我所发现的(通过混乱)是这样的:
#include <iostream>
using namespace std;
int main()
{
int * pointer;
pointer = new int;
pointer[2] = 1932; // pointer [2] exists? and i can assign to it?!
cout << pointer[2] << endl; // ... and access it successfully?!
};
事实上,我可以下标 pointer
告诉我到目前为止,pointer = new int
隐式创建了一个数组。但如果是这样,那么它的尺寸是多少?
如果有人能帮我解决这一切,我将不胜感激......
In many tutorials, the first code samples about dynamic memory start along the lines of:
int * pointer;
pointer = new int; // version 1
//OR
pointer = new int [20]; // version 2
They always proceed to explain how the second version works, but totally avoid talking about the first version.
What I want to know is, what does pointer = new int
create? What can I do with it? What does it mean? Every tutorial without fail will avoid talking about the first version entirely. All I've found out (through messing about) is this:
#include <iostream>
using namespace std;
int main()
{
int * pointer;
pointer = new int;
pointer[2] = 1932; // pointer [2] exists? and i can assign to it?!
cout << pointer[2] << endl; // ... and access it successfully?!
};
The fact that I can subscript pointer
tells me so far that pointer = new int
implicitly creates an array. But if so, then what size is it?
If someone could help clear this all up for me, I'd be grateful...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
我的老师是这样解释的。
想想电影。实际的席位是内存分配,而你得到的票是指针。
这将是一家有一个座位的电影院,指针将是该座位的门票
。 这将是一家有 20 个座位的电影院,指针将是前往第一个座位的门票。指针[1]是第二个座位的票,指针[19]是最后一个座位的票。
当您执行
int*pointer = new int;
然后访问pointer[2]
时,您会让某人坐在过道上,这意味着未定义的行为My teacher explained it like this.
Think of cinema. The actual seats are memory allocations and the ticket you get are the pointers.
This would be a cinema with one seat, and pointer would be the ticket to that seat
This would be a cinema with 20 seats and pointer would be the ticket to the first seat. pointer[1] would be the ticket to the second seat and pointer[19] would be the ticket to the last seat.
When you do
int* pointer = new int;
and then accesspointer[2]
you're letting someone sit in the aisle, meaning undefined behaviour对于初学者来说,这是 C 和 C++ 中的典型错误。第一句话创建一个空间来容纳一个
int
。第二个创建一个空间来容纳其中 20 个int
。然而,在这两种情况下,它都会将动态保留区域的开头地址分配给指针变量。更令人困惑的是,即使它们指向的内存无效,您也可以使用索引访问指针(如您放置的
pointer[2]
)。在这种情况下:您可以访问
pointer[2]
,但您会出现未定义的行为。请注意,您必须检查这些访问实际上并未发生,并且编译器在防止此类错误方面通常无能为力。This is a typical error in C and C++ for beginners. The first sentence, creates a space for holding just an
int
. The second one creates a space for holding 20 of thoseint
s. In both cases, however, it assigns the address of the beginning of the dynamically-reserved area to thepointer
variable.To add to the confusion, you can access pointers with indices (as you put
pointer[2]
) even when the memory they're pointing is not valid. In the case of:you can access
pointer[2]
, but you'd have an undefined behavior. Note that you have to check that these accesses don't actually occur, and the compiler can do usually little in preventing this type of errors.这仅创建一个整数。
这将创建 20 个整数。
下面的内容无效,因为pointer[2] 转换为 *(pointer + 2) ;尚未创建/分配。
干杯!
This creates only one integer.
This creates 20 integers.
The below is invalid, since pointer[2] translates as *(pointer + 2) ; which is not been created/allocated.
Cheers!
new int[20]
为大小为 20 的整数数组分配内存,并返回指向它的指针。new int
只是为一个整数分配内存,并返回指向它的指针。隐含地,这与new int[1]
相同。您可以在两个指针上取消引用(即使用
*p
),但只能在new int[20]返回的指针上使用
。p[i]
p[0]
仍然适用于两者,但您可能会搞砸并意外地输入错误的索引。更新:另一个区别是您必须对数组使用
delete[]
,对整数使用delete
。new int[20]
allocates memory for an integer array of size 20, and returns a pointer to it.new int
simply allocates memory for one integer, and returns a pointer to it. Implicitly, that is the same asnew int[1]
.You can dereference (i.e. use
*p
) on both pointers, but you should only usep[i]
on the pointer returned by thenew int[20]
.p[0]
will still work on both, but you might mess up and put a wrong index by accident.Update: Another difference is that you must use
delete[]
for the array, anddelete
for the integer.pointer = new int
在堆上分配足够的内存来存储一个int
。pointer = new int [20]
分配内存来存储20个int
。两个调用都返回指向新分配的内存的指针。
注意:不要依赖于初始化分配的内存,它可能包含随机值。
pointer = new int
allocates enough memory on the heap to store oneint
.pointer = new int [20]
allocates memory to store 20int
s.Both calls return a pointer to the newly allocated memory.
Note: Do not rely on the allocated memory being initialized, it may contain random values.
pointer = new int;
分配一个整数并将其地址存储在pointer
中。pointer[2]
是pointer + 2
的同义词。要理解它,请阅读指针算术。这行实际上是未定义的行为,因为您正在访问之前未分配的内存,并且它可以工作是因为您很幸运。pointer = new int;
allocates an integer and stores it's address inpointer
.pointer[2]
is a synonym forpointer + 2
. To understand it, read about pointer arithmetic. This line is actually undefined behavior, because you are accessing memory that you did not previously allocate, and it works because you got lucky.int* p = new int
为一个整数分配内存。它不会隐式创建数组。当您写入无效的内存位置时,使用 p[2] 访问指针的方式将导致未定义的行为。仅当使用new[]
语法时才能创建数组。在这种情况下,您需要使用delete[]
释放内存。如果您使用new
分配了内存,则意味着您正在创建单个对象,并且需要使用delete
释放内存。int* p = new int
allocates memory for one integer. It does not implictly create an array. The way you are accessing the pointer usingp[2]
will cause the undefined behavior as you are writing to an invalid memory location. You can create an array only if you usenew[]
syntax. In such a case you need to release the memory usingdelete[]
. If you have allocated memory usingnew
then it means you are creating a single object and you need to release the memory usingdelete
.*“到目前为止,我可以为指针添加下标这一事实告诉我,我
pointer = new int
隐式创建了一个数组。但如果是这样,那么它的大小是多少?”*
这是问题中我最喜欢的部分,也是您强调的。
众所周知,动态内存分配利用了特定于给定程序的堆栈空间。
当我们仔细研究 new 运算符的定义时:-
这实际上表示特定大小的对象数组,如果成功,那么它会自动构造数组中的每个对象。因此,我们可以自由使用大小范围内的对象,因为它已经被初始化/构造了。
另一方面,对于上面的示例,当
使用任何一个时,都有可能出现未定义的行为。虽然可以使用指针访问特定的内存位置,但不能保证,因为未创建或构造相同的特定对象。这可以被认为是未在堆栈上为特定程序分配的空间。
希望这有帮助。
*"The fact that i can subscript pointer tells me so far that I
pointer = new int
implicitly creates an array. but if so, then what size is it?"*
This was the part of the question which I liked the most and which you emphasize upon.
As we all know dynamic memory allocation makes use of the space on the Stack which is specific to the given program.
When we take a closer look onto the definition of new operator :-
This actually represents an array of objects of that particular size and if this is successful, then it automatically Constructs each of the Objects in the array. Thus we are free to use the objects within the bound of the size because it has already been initialized/constructed.
On the other hand for the above example there's every possibility of an undefined behaviour when any of
are used. Though the particular memory location can be accessed with the use of pointers, there's no guarantee because the particular Object for the same was not created nor constructed.This can be thought of as a space which was not allocated on the Stack for the particular program.
Hope this helps.
它不创建数组。它创建一个整数并返回指向该整数的指针。当您编写指针[2]时,您引用的是尚未分配的内存。你需要小心,不要这样做。该内存可以通过外部程序进行编辑,我相信您不需要。
It does not create array. It creates a single integer and returns the pointer to that integer. When you write pointer[2] you refer to a memory which you have not allocated. You need to be carefull and not to do this. That memory can be edited from the external program which you, I belive, don't want.
教程没有告诉您如何处理它的原因是它真的完全毫无用处!它分配一个
int
并给你一个指向它的指针。问题是,如果你想要一个 int,为什么不直接声明一个呢?
The reason the tutorial doesn't rell you what to do with it is that it really is totally useless! It allocates a single
int
and gives you a pointer to that.The problem is that if you want an int, why don't you just declare one?