C++ 如何解决上次删除[]P;代码中的行?
我尝试了很多在互联网上搜索的方法,但没有一个有用的可能是因为我不能问正确的问题,所以请帮助解释当前的问题和任何问题,我可能会面临接近这个thx提前C++ 如何解决上次删除[]P;代码中的行?,c++,C++,我尝试了很多在互联网上搜索的方法,但没有一个有用的可能是因为我不能问正确的问题,所以请帮助解释当前的问题和任何问题,我可能会面临接近这个thx提前 #include <iostream> using namespace std; int main() { int i,n; //1 - Automatic array allocation (The size of array is known before run -
#include <iostream>
using namespace std;
int main()
{
int i,n;
//1 - Automatic array allocation (The size of array is known before run - constant) ------------
int A[10];
cout<< "\nValue of variable A=" << A<< " ('Roughly Speaking' Array name is a constant pointer )";
for(i=0; i<10; i++)
A[i]=2*i;
cout<<"\nValues of the array A: ";
for(i=0; i<10; i++)
cout<<A[i]<<" ";
//Using pointers to access array elements
int* P=A;
P[0]=99;
P[9]=888;
cout<<"\n\nValues of the array A: ";
for(i=0; i<10; i++)
cout<<A[i]<<" ";
cout<<"\n\nEnter the number of array elements:";
cin>>n;
//The new opertor. (dynamic allocation)
P=new int[n];
for(i=0; i<n; i++)
P[i]=5*i;
cout<<"\n\nValues of the array pointed to by pointer P:\n";
for(i=0; i<n; i++)
cout<<P[i]<<" ";
//To free the array memory. notice the square brackets
delete [] P;
//P=NULL; //Note: good to set P = NULL after deletion
cout<<"\n\nValues of the array pointed by pointer P (after delete):\n";
for(i=0; i<n; i++)
cout<<P[i]<<" ";
cout<<"\n\nDeleting pointer P does not mean you can not use it again";
P = A+4;
cout<<"\nP[0]="<<P[0]<<", A[4]="<<A[4];
cout<<"\nP[5]="<<P[5]<<", A[9]="<<A[9];
A[3] = 6;
//for(int j=0;j<10;j++)
//{
// delete P[j];
//}
delete [] P; //--------------here the problem
cout<<endl;
getchar();
return 0;
}
#包括
使用名称空间std;
int main()
{
inti,n;
//1-自动数组分配(数组大小在运行前已知-常量)------------
INTA[10];
在第一个delete[]p
之前(包括第一个delete[]p
),代码没有问题。但是一旦调用了delete[]
,p
将指向无效内存,因此访问p[i]
的下一个循环具有未定义的行为:
P=new int[n];
...
delete [] P; // <-- P IS LEFT POINTING AT INVALID MEMORY!!!
...
for(i=0; i<n; i++)
cout<<P[i]<<" "; // <-- UNDEFINED BEHAVIOR!!!
切勿调用delete
或delete[]
来释放未分别使用new
或new[]
分配的内存。因此,要清除指针,我只需将其等于NULL?对于行“p更新为指向“i not get it xd”的第5个元素,无需“清除指针”在删除它之后。如果要将其设置为NULL,这是您的选择,它是可选的。至于P=A+4
,这与执行P=&A[4]完全相同
,只使用指针算术。当您单独引用固定大小数组的名称时,它会衰减为指向数组中第一个元素的指针。向指针添加一个整数N
会使指针向前移动N
元素数(即sizeof(element)*N
字节).当你有一个指向某个表示序列元素数组的指针时,这是合法的。啊,我现在明白了,谢谢你的帮助
P = A+4; // <-- NO new[] HERE!!
...
delete [] P; // <-- BOOM!!!