更改动态分配的数组的指针(changing pointer of a dynamically allocated array)

编程入门 行业动态 更新时间:2024-10-26 23:41:05
更改动态分配的数组的指针(changing pointer of a dynamically allocated array)

当我们像这样动态地声明一些东西时

int *ptr = new int [100];

然后更改指针地址(即指向其他地址)

int pointer[5] = {1,2,1,3,1,}; ptr = pointer ;

那么包含100个整数的内存会发生什么?

无论如何重新控制那段记忆? 如果没有,是否会导致内存泄漏?

When we declare something dynamically like this

int *ptr = new int [100];

and then change the pointer address (i.e point it to something else)

int pointer[5] = {1,2,1,3,1,}; ptr = pointer ;

now what happens to that memory which contained 100 integers?

is there anyway to regain control of that memory ? and if not, does it lead to a memory leak?

最满意答案

那么包含100个整数的内存会发生什么?

它被“泄露”,因为你失去了你唯一的手柄。

无论如何重新控制那段记忆?

不,除非你在重新分配ptr之前注意创建另一个句柄。

int* ptr = new int[100]; int* ptr2 = ptr; ... ptr = pointer; delete [] ptr2;

在实际代码中,您不会依赖原始指针来分配内存,而是使用最适合您问题的RAII类型(例如std::vector , std::unique_ptr等)

now what happens to that memory which contained 100 integers?

It is "leaked" because you lost the only handle you had to it.

is there anyway to regain control of that memory ?

No, unless you take care to create another handle before re-assigning ptr.

int* ptr = new int[100]; int* ptr2 = ptr; ... ptr = pointer; delete [] ptr2;

In real code you would not rely on raw pointers to allocated memory, but rather use whichever RAII type works best for your problem (e.g. std::vector, std::unique_ptr etc.)

更多推荐

本文发布于:2023-08-03 07:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   动态分配   changing   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!