c ++什么是“指针=新类型”而不是“指针=新类型[]”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6043689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:23:36  来源:igfitidea点击:

c++ what is "pointer = new type" as opposed to "pointer = new type []"?

c++arraysdynamic-memory-allocationnew-operator

提问by code shogan

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 intcreate? 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:

我想知道的是,什么是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?!
};

The fact that I can subscript pointertells me so far that pointer = new intimplicitly creates an array. But if so, then what size is it?

pointer到目前为止,我可以下标的事实告诉我pointer = new int隐式创建了一个数组。但如果是这样,那么它的大小是多少?

If someone could help clear this all up for me, I'd be grateful...

如果有人能帮我解决这一切,我将不胜感激......

采纳答案by Diego Sevilla

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 those ints. In both cases, however, it assigns the address of the beginning of the dynamically-reserved area to the pointervariable.

这是初学者在 C 和 C++ 中的典型错误。第一句,创建了一个空间来容纳一个int. 第二个创建了一个空间来容纳其中的 20 个int。然而,在这两种情况下,它都将动态保留区域的开始地址分配给pointer变量。

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:

pointer[2]更令人困惑的是,即使它们指向的内存无效,您也可以访问带有索引的指针(如您所放)。如果是:

int* pointer = new int;

you can access pointer[2], but you'd have an undefined behavior. Note that youhave to check that these accesses don't actually occur, and the compiler can do usually little in preventing this type of errors.

你可以访问pointer[2],但你会有一个未定义的行为。请注意,必须检查这些访问实际上并未发生,并且编译器在防止此类错误方面通常无能为力。

回答by Default

My teacher explained it like this.
Think of cinema. The actual seats are memory allocations and the ticket you get are the pointers.

我的老师是这样解释的。
想想电影。实际座位是内存分配,你得到的票是指针。

int * pointer = new int;

This would be a cinema with one seat, and pointer would be the ticket to that seat

这将是一个只有一个座位的电影院,指针将是该座位的门票

pointer = new int [20] 

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.

这将是一个有 20 个座位的电影院,指针将是第一个座位的门票。指针[1] 将是第二个座位的票,指针[19] 将是最后一个座位的票。

When you do int* pointer = new int;and then access pointer[2]you're letting someone sit in the aisle, meaning undefined behaviour

当您这样做int* pointer = new int;然后访问时,pointer[2]您是在让某人坐在过道上,这意味着未定义的行为

回答by Ricko M

This creates only one integer.

这只会创建一个整数。

pointer = new int;        // version 1

This creates 20 integers.

这将创建 20 个整数。

pointer = new int [20]    // version 2

The below is invalid, since pointer[2] translates as *(pointer + 2) ; which is not been created/allocated.

以下无效,因为 pointer[2] 翻译为 *(pointer + 2) ;未创建/分配。

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 succesfuly?!
};

Cheers!

干杯!

回答by evgeny

new int[20]allocates memory for an integer arrayof size 20, and returns a pointer to it.

new int[20]为大小为20的整数数组分配内存,并返回指向它的指针。

new intsimply allocates memory for oneinteger, and returns a pointer to it. Implicitly, that is the same as new int[1].

new int简单地为一个整数分配内存,并返回一个指向它的指针。隐含地,这与new int[1].

You can dereference (i.e. use *p) on both pointers, but you should only use p[i]on the pointer returned by the new int[20].

您可以*p在两个指针上取消引用(即使用),但您应该只p[i]在由 返回的指针上使用new int[20]

p[0]will still work on both, but you might mess up and put a wrong index by accident.

p[0]仍然适用于两者,但您可能会搞砸并意外放置错误的索引。

Update: Another difference is that you must use delete[]for the array, and deletefor the integer.

更新:另一个区别是您必须delete[]用于数组和delete整数。

回答by Tony the Pony

pointer = new intallocates enough memory on the heap to store one int.

pointer = new int在堆上分配足够的内存来存储一个int.

pointer = new int [20]allocates memory to store 20 ints.

pointer = new int [20]分配内存来存储 20int秒。

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.

注意:不要依赖正在初始化的分配内存,它可能包含随机值。

回答by Bj?rn Pollex

pointer = new int;allocates an integer and stores it's address in pointer. pointer[2]is a synonym for pointer + 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.

pointer = new int;分配一个整数并将其地址存储在pointer. pointer[2]是 的同义词pointer + 2。要理解它,请阅读指针运算。这一行实际上是未定义的行为,因为您正在访问以前未分配的内存,并且它起作用是因为您很幸运。

回答by NirmalGeo

*"The fact that i can subscript pointer tells me so far that I pointer = new intimplicitly creates an array. but if so, then what size is it?"*

* “到目前为止,我可以下标指针的事实告诉我,我pointer = new int隐式地创建了一个数组。但如果是这样,那么它的大小是多少?” *

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 :-

众所周知,动态内存分配利用堆栈上特定于给定程序的空间。当我们仔细研究新运算符的定义时:-

void* operator new[] (std::size_t size) throw (std::bad_alloc);

This actually represents an array of objects of that particular size and if this is successful, then it automatically Constructseach 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.

这实际上代表了一个特定大小的对象数组,如果成功,那么它会自动构造数组中的每个对象。因此我们可以自由使用大小范围内的对象,因为它已经被初始化/构造。

int * pointer = new int;

On the other hand for the above example there's every possibility of an undefined behaviour when any of

另一方面,对于上面的例子,当任何一个

*(pointer + k) or *(k + pointer)

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.

希望这可以帮助。

回答by Bo Persson

int * pointer; pointer = new int;  // version 1
//OR 
pointer = new int [20]             // version 2 

what I want to know is, what does pointer = new intcreate? what can I do with it? what does it mean? Every tutorial without fail will avoid talking about the first version entirely

我想知道的是,pointer = new int创造了什么?我能用它做什么?这是什么意思?每个教程都不会失败,完全避免谈论第一个版本

The reason the tutorial doesn't rell you what to do with it is that it really istotally useless! It allocates a single intand gives you a pointer to that.

本教程不RELL你怎么用它做的原因是,它真的完全没用!它分配一个单一的,int并给你一个指向它的指针。

The problem is that if you want an int, why don't you just declare one?

问题是,如果你想要一个 int,为什么不直接声明一个呢?

int i;

回答by Narek

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.

它不创建数组。它创建一个整数并返回指向该整数的指针。当您编写指针 [2] 时,您指的是尚未分配的内存。你需要小心,不要这样做。可以从外部程序编辑该内存,我相信您不想要。

回答by Naveen

int* p = new intallocates memory for oneinteger. It does not implictly create an array. The way you are accessing the pointer using p[2]will cause the undefined behavior as you are writing to an invalid memory location. You can create an array only if you use new[]syntax. In such a case you need to release the memory using delete[]. If you have allocated memory using newthen it means you are creating a single object and you need to release the memory using delete.

int* p = new int一个整数分配内存。它不会隐式地创建一个数组。p[2]当您写入无效的内存位置时,您访问指针的方式将导致未定义的行为。只有使用new[]语法才能创建数组。在这种情况下,您需要使用delete[]. 如果您已使用分配内存,new则意味着您正在创建单个对象,并且您需要使用delete.