I have written a program in C++ to delete an element in a dynamically allocated array. I can see the array with the deleted element but after that, it produces some errors which I can't understand. I have included the images to the error as I wasn't able to copy the error message. I'm using:
Debian 9, 32 bit
Compiler clang.
IDE code::blocks.
The code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int *ar,arsize,lp1,lp2,lp3,lp4,ele,pos;
ar=nullptr;
cout<<"enter the size of array to be created:- "; cin>>arsize;
ar=new int[arsize];
if(!ar)
{
cout<<"Aborting";
exit(1);
}
else
{
cout<<"enter the elements for array:- ";
for(lp1=0;lp1<arsize;lp1++)
{
cin>>ar[lp1];
}
cout<<"Enter element to be deleted:- "; cin>>ele;
for(lp2=0;lp2<arsize;lp2++)
{
if(ar[lp2]==ele)
{
ar[lp2]=0;
pos=lp2;
break;
}
}
for(lp3=pos;lp3<arsize;lp3++)
{
ar[lp3]=ar[lp3+1];
}
ar[arsize]=0;
cout<<"new array is:-"<<endl;
for(lp4=0;lp4<arsize-1;lp4++)
{
cout<<"\t"<<ar[lp4]<<endl;
}
delete[]ar;
return 0;
}
}
You are trying to access ar[arsize]
, which doesn't exist.
Remember, C++ arrays are 0 indexed.
So try ar[arsize-1]
instead