简体   繁体   English

删除动态分配的数组

[英]Deleting dynamically allocated array

I am a beginner in C++ and I have a doubt. 我是C ++的初学者,我对此表示怀疑。 If I have a code like this: 如果我有这样的代码:

int* f(int n){               //global

int* arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=i;

return arr;
}

void main() {

int n;
scanf("%d",&n);


int* arr1 = new int;  //or should I write just int* arr1; ?
arr1 = f(n);

delete [] arr1;  // or just delete arr1;
}

The question is should I delete arr1 as array or not since I declared it as pointer to int? 问题是因为我将arr1声明为指向int的指针,所以应该删除arr1作为数组吗? The code doesn't make much sense but it is good as an example. 该代码没有多大意义,但作为示例很好。 I know there are a lot of similar question but I could not find the exact answer to my question. 我知道有很多类似的问题,但是我找不到确切的答案。

If the allocation was made with new <type>[n] then the deallocation must be made with delete [] . 如果使用new <type>[n]进行分配,则必须使用delete []进行释放。

All that counts when determining the correct form of delete is the form of new that was used in the allocation. 确定正确的delete形式时,最重要的是分配中使用的new形式。

In your main function, you leak memory. main功能中,您会泄漏内存。 You initialize arr1 with a call to new and then immediately overwrite that value with the new pointer returned by the call to f() . 您可以通过调用new初始化arr1 ,然后立即使用f()调用返回的新指针覆盖该值。 The call to new from main is simply wrong and should be removed. main调用new完全是错误的,应该删除。 Write it simply like this: 像这样简单地写:

int* arr1 = f(n);

And your main should be 而你的main应该是

int main()

Write

int* arr1 = f(n);

and later 然后

delete[] arr1;

the array object is allocated in f() , and delete deletes it. 数组对象在f()分配,而delete删除它。 The pointer itself can not be deleted, just the object(array) it points to. 指针本身不能删除,只能删除它指向的对象(数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM