简体   繁体   English

指针和数组的删除行为不同

[英]Behavior of delete different for a pointer and array

I stumbled on this problem while tinkering with old school arrays.我在修补老式阵列时偶然发现了这个问题。 An interesting one though:一个有趣的:

a[] = {1,2,3,4,5};
a[][] = {{1,2,3,4}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}}

Consider 2 scenarios:考虑两种情况:

1.) 1.)

void func(int *a) { //passing a 1D array
   a[1] = 100; //modified an element here
   delete a;  //This would have no effect on the array outside this function. 
}

2.) 2.)

void func(int (*a)[4]) { //passing a 2D array
   a[1][2] = 100; //modified an element here of 2D array
   delete a;  //Would have an effect on the outside. Would delete a[0][0]'s memory outside.
} 

Question is why?问题是为什么? In 1.) pointer shall point to an array variable memory hence, the delete signature won't clear the memory a[0]?在 1.) 中,指针应指向数组变量内存,因此删除签名不会清除内存 a[0]?

In 2.) the signature of parameter and passed variable match exactly hence the delete would indeed delete the memory held by local variable? 2.) 参数的签名和传递的变量完全匹配,因此删除确实会删除局部变量持有的内存?

Any pointers here?这里有什么指点吗?

You're invoking undefined behavior on multiple levels.您正在多个级别调用未定义的行为。 Calling delete on an array rather than delete[] ...and calling any form of delete on an object not allocated with new .在数组上调用delete而不是delete[] ...并在未分配给new的对象上调用任何形式的delete

Your program can do anything it wants.你的程序可以做任何它想做的事情。

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

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