C++ 指向结构体的数组指针 动态分配内存后如何删除

来源:百度知道 编辑:UC知道 时间:2024/06/08 13:25:49
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<iomanip.h>
#include<math.h>
struct point
{
int x,y;
int flag;//按极角排序的下标
int real;
};
void main()
{
//随机情况下的测试
int n;
cout<<"1.利用随机函数产生[x(-100,100),y(-100,100)]内的n个点坐标,请输入n(n<10000):";
cin>>n;
point *p;
p=new point[n];
srand(time(NULL));
for(int i=1;i<=n;i++)
{
p[i].x=pow(-1,rand())*rand()/1000;
p[i].y=pow(-1,rand())*rand()/1000;
p[i].flag=i;
}
cout<<endl<<"2.生成的随机点为"<<endl;
int count=0;
for(i=1;i<=n;i++)
{
cout<<"("<<setw(2)<<p[i].x<<","<<setw(2)<<p[i].y<<")"<<" ";
count++;
if(count%5==0)
cout<<endl;
}

动态创建数组举例:
int **t=new int *[3];//行
for(int i=0;i<3;i++)
{
t[i]=new int[5];//列
}
动态删除数组举例:
for(int i=0;i<3;i++)
{
delete[5]t[i];
t[i]=NULL;
}
t=NULL;
程序举例:
#include <iostream>
using namespace std;
void main()
{
int **t;
t=new int *[3];
for(int i=0;i<3;i++)
t[i] = new int[5];
for(int i=0;i<3;i++)
for(int j=0;j<5;j++)
t[i][j]=i+j;
for(int i=0;i<3;i++)
{for(int j=0;j<5;j++)
cout<<t[i][j]<<" ";
cout<<endl;
}
for(int i=0;i<3;i++)
{
delete [5]t[i];
t[i]=NULL;
}
delete [3]t;
t=NULL;
}
以上均来自互联网,如果有侵权,联系以便保证你的利益

LS的如果不知道请不要随便误导别人哦
其实你这个内存分配没错,但是你的内存访问出错了,小哥,你应该知道数组的计数是从0开始的吧?比如说数组 int a[2],那么2个元素就是a[0],a[1],没有a[2]哦,所以
for(int i=1;i<=n;i++)
{
p[i].x=pow(-1,rand())*rand()/1000;
p[i].y=pow(-1