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

时间:2020-12-22 16:28:11

in many turorials the first code samples about dynamic memory start along the lines of:

在许多turorials中,关于动态内存的第一个代码示例从以下几行开始:

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:

我想知道的是,指针= 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 succesfuly?!
};

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?

我可以给指针加上下标的事实告诉我,到目前为止,我的指针= new int隐式地创建了一个数组。但如果是的话,它的尺寸是多少?

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

如果有人能帮我清除这一切,我会很高兴……

10 个解决方案

#1


13  

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 pointer variable.

对于初学者来说,这是一个典型的C和c++错误。第一个句子,创造一个容纳一个int的空间。第二个句子创造一个容纳20个ints的空间。然而,在这两种情况下,它都将动态保留区域开头的地址赋给指针变量。

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:

为了增加混乱,您可以访问带有索引的指针(当您放置指针[2]时),即使它们所指向的内存是无效的。的情况:

int* pointer = new int;

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.

您可以访问指针[2],但是您将有一个未定义的行为。请注意,您必须检查这些访问实际上没有发生,编译器通常在防止此类错误方面做的很少。

#2


9  

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.

下面是无效的,因为指针[2]翻译为*(指针+ 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!

干杯!

#3


9  

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;然后访问指针[2]你让某人坐在过道里,意思是没有定义的行为

#4


2  

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

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

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

新int仅仅为一个整数分配内存,并返回一个指向它的指针。隐式地,它与新的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),但是您应该只对新int[20]返回的指针使用p[i]。

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 delete for the integer.

更新:另一个不同之处是,必须对数组使用delete[],对整数使用delete。

#5


1  

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

指针=新int在堆上分配足够的内存来存储一个int。

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

指针=新的int[20]分配内存来存储20个ints。

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.

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

#6


1  

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.

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

#7


1  

*"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?" *

*“我可以给指针加上下标的事实告诉我,到目前为止,我的指针= 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 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.

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

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.

希望这个有帮助。

#8


0  

int* p = new int allocates memory for one integer. 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 new then it means you are creating a single object and you need to release the memory using delete.

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

#9


0  

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]时,您将引用未分配的内存。你要小心,不要这样做。这个记忆可以从你,我相信,不需要的外部程序中编辑出来。

#10


0  

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

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

我想知道的是,指针= new 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?

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

int i;

#1


13  

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 pointer variable.

对于初学者来说,这是一个典型的C和c++错误。第一个句子,创造一个容纳一个int的空间。第二个句子创造一个容纳20个ints的空间。然而,在这两种情况下,它都将动态保留区域开头的地址赋给指针变量。

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:

为了增加混乱,您可以访问带有索引的指针(当您放置指针[2]时),即使它们所指向的内存是无效的。的情况:

int* pointer = new int;

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.

您可以访问指针[2],但是您将有一个未定义的行为。请注意,您必须检查这些访问实际上没有发生,编译器通常在防止此类错误方面做的很少。

#2


9  

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.

下面是无效的,因为指针[2]翻译为*(指针+ 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!

干杯!

#3


9  

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;然后访问指针[2]你让某人坐在过道里,意思是没有定义的行为

#4


2  

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

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

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

新int仅仅为一个整数分配内存,并返回一个指向它的指针。隐式地,它与新的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),但是您应该只对新int[20]返回的指针使用p[i]。

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 delete for the integer.

更新:另一个不同之处是,必须对数组使用delete[],对整数使用delete。

#5


1  

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

指针=新int在堆上分配足够的内存来存储一个int。

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

指针=新的int[20]分配内存来存储20个ints。

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.

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

#6


1  

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.

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

#7


1  

*"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?" *

*“我可以给指针加上下标的事实告诉我,到目前为止,我的指针= 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 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.

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

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.

希望这个有帮助。

#8


0  

int* p = new int allocates memory for one integer. 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 new then it means you are creating a single object and you need to release the memory using delete.

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

#9


0  

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]时,您将引用未分配的内存。你要小心,不要这样做。这个记忆可以从你,我相信,不需要的外部程序中编辑出来。

#10


0  

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

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

我想知道的是,指针= new 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?

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

int i;