Delete Operator Is not working the program crash at the end

int main()
{
int vnum = 0;
VEHICLE *vehiptr;
VEHICLE *dptr;
cout<<"Please enter the number of vehicle: ";
cin>>vnum;
vehiptr = new VEHICLE[vnum];
dptr = vehiptr;
for(int a=1;a<=vnum;a++)
{
vehiptr->get_input();
if(a<vnum)
{
vehiptr++;
}
}
for(int i =1;i<=vnum;i++)
{
dptr->display();
if(i<vnum)
{
dptr++;
}


}
delete [] vehiptr;
vehiptr is no longer pointing to the first element of the array. The pointer value that you pass to delete has to be the same pointer value that was returned from new.
Last edited on
ok please give me a correct code please
this code is working but can i do better then that
int main()
{
int vnum = 0;
VEHICLE* vehiptr;
VEHICLE *dptr;
VEHICLE * zptr;
cout<<"Please enter the number of vehicle: ";
cin>>vnum;
vehiptr = new VEHICLE[vnum];
dptr = vehiptr;
zptr = dptr;
for(int a=1;a<=vnum;a++)
{
dptr->get_input();
if(a<vnum)
{
dptr++;
}
}
for(int i =1;i<=vnum;i++)
{
zptr->display();
if(i<vnum)
{
zptr++;
}


}

delete [] vehiptr;
system("pause");

}
Instead of having a lot of pointers you could use the subscript operator.
1
2
3
4
for(int a=0;a<vnum;a++)
{
	vehiptr[a].get_input();
}


but what about the increment of the pointer i think that is casing the problem when i increment vehiptr++
If you do it like this you don't need to increment the pointer.
you mean like this by doing that i got heap corruption error
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
int vnum = 0;
	VEHICLE* vehiptr;
	cout<<"Please enter the number of vehicle: ";
	cin>>vnum;
	vehiptr = new VEHICLE[vnum];
	for(int a=1;a<=vnum;a++)
	{
	vehiptr[a].get_input();

	}
	for(int i =1;i<=vnum;i++)
	{
		vehiptr[i].display();
	}

	delete [] vehiptr;
system("pause");

}
Array indices starts at 0 so vehiptr[0] is the first element in the array and vehiptr[vnum - 1] is the last element in the array.
Last edited on
Thanks a lot
Topic archived. No new replies allowed.