c++什么是“指针=新类型”与“指针=新类型[]”相反?

发布于 2024-11-08 11:20:19 字数 736 浏览 3 评论 0原文

在许多教程中,关于动态内存的第一个代码示例都是这样开始的:

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 技术交流群。

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

发布评论

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

评论(10

时光病人 2024-11-15 11:20:19

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

int * pointer = new int;

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

pointer = new int [20] 

。 这将是一家有 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.

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.

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

骑趴 2024-11-15 11:20:19

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

更令人困惑的是,即使它们指向的内存无效,您也可以使用索引访问指针(如您放置的pointer[2])。在这种情况下:

int* pointer = new int;

您可以访问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 those ints. In both cases, however, it assigns the address of the beginning of the dynamically-reserved area to the pointer 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:

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.

随梦而飞# 2024-11-15 11:20:19

这仅创建一个整数。

pointer = new int;        // version 1

这将创建 20 个整数。

pointer = new int [20]    // version 2

下面的内容无效,因为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?!
};

干杯!

This creates only one integer.

pointer = new int;        // version 1

This creates 20 integers.

pointer = new int [20]    // version 2

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

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!

怀念你的温柔 2024-11-15 11:20:19

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 as 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[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, and delete for the integer.

漫漫岁月 2024-11-15 11:20:19

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

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

两个调用都返回指向新分配的内存的指针。

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

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

pointer = new int [20] allocates memory to store 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.

谈场末日恋爱 2024-11-15 11:20:19

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

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.

野の 2024-11-15 11:20:19

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

┈┾☆殇 2024-11-15 11:20:19

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

这是问题中我最喜欢的部分,也是您强调的。

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

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

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

int * pointer = new int;

另一方面,对于上面的示例,当

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

使用任何一个时,都有可能出现未定义的行为。虽然可以使用指针访问特定的内存位置,但不能保证,因为未创建或构造相同的特定对象。这可以被认为是未在堆栈上为特定程序分配的空间。

希望这有帮助。

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

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.

舂唻埖巳落 2024-11-15 11:20:19

它不创建数组。它创建一个整数并返回指向该整数的指针。当您编写指针[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.

数理化全能战士 2024-11-15 11:20:19
int * pointer; pointer = new int;  // version 1
//OR 
pointer = new int [20]             // version 2 

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

教程没有告诉您如何处理它的原因是它真的完全毫无用处!它分配一个int并给你一个指向它的指针。

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

int i;
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

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