delete [ ] values;
what is this.tell me about this.
|
For every call with 'new' you must call 'delete' to free data that pointer point at.
If you don't call delete on first insert function you'll get memory leak. But if it is insisted to
write code as if it is in comments then do so (even if its wrong). Also you got undeclared identifier 'i' that
you used in loop. I don't know witch compiler you are using (or forced to use) but it might asign default type
as int.
In second insert function part 3 you need to open braces after if statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void insert(int index, T value)
{
if(index<0||index>size)
return;
if(size==0&&index!=1)
return;
if(size==0&&index==0)
{
values=new T[1];
values[0]=value;
size++;
return;
}
T *temp=new T[size+1];
for(int i=0; i <= index-1; i++) // i <= index - 1
temp[i]=values[i];
temp[index] = value;//temp[value]; <-wrong
for(i=index;i<=size-1;i++)// i <= size - 1
temp[i+1]=values[i];
values=temp;
size++;
}
| |
note that you again have memory leak if you don't call delete.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void remove()
{
if(size==0)
return;
if(size==1)
{ //braces added
size=0;
values=NULL;
return;
}
T *temp=new T[size-1];
for(i=0;i<=size-2;i++)//same as insert '<='
temp[i]=values[i];
values=temp;
size--;
}
| |
again memory leak without delete
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void remove(int index)
{
if(size==0)
return;
if(index<0||index>size)
return;
if(size==1&&index!=0)
return;
if(size==1)
{ //braces again
size=0;
values=NULL;
return;
}
T *temp=new T[size-1];
for(i=0;i<=index-1;i++)
temp[i]=values[i];
for(i=index;i <= size-1;i++)
temp[i]=values[i+1];
values=temp;
size--;
}
| |
also leak without delete.
EDIT <offtopic>:
Please Experts Check all the mistakes in the code and correct the mistakes.
|
I am not an expert, i am also a beginner with c++. I didn't even have any programming language at school, this is my hobby.
So that you know that any code that i provide might not be reliable.