deleting array of pointers

What is wrong with the code below?
Goal games[4]={Goal(1,"one"),Goal(2,"two"),Goal(3,"three"),Goal(4,"four")};

Goal **games1;
games1=new Goal*;

games1[0]=&games[0];
games1[1]=&games[1];
games1[2]=&games[2];
games1[3]=&games[3];

for(int i=0;i<4;i++)
{delete games1[i];}


i get the following warning:block_type_is_invalid(phead-.nblock in use)
thanks
Last edited on
games[0..3] are objects created in the stack. Attempting to delete them causes a segmentation fault.
You can try it with a much shorter code:
1
2
int a;
delete &a;


There's also a second bug. games1 points to a single pointer. These lines
1
2
3
games1[1]=&games[1];
games1[2]=&games[2];
games1[3]=&games[3];
cause a buffer overflow. It may cause the program to crash in some systems.
Last edited on
Thanks,
Now tell me:what is the best way that games1 can point to games, so every [i] on games1 will point to [i] on games array?
an array name without brackets gives you a pointer to the array. So if you want a pointer 'games1' to point to array 'games', then you can do the following:

 
Goal* games1 = games;


games1[i] will then be the same 'Goal' object as games[i]
Last edited on
1
2
3
Goal **games1=new Goal *[4];
for (int a=0;a<4;a++)
    games1[a]=games+a; //Note: a[b]==*(a+b), so &a[b]==&*(a+b)==a+b 
Thanks guys, very helpfull!!
Topic archived. No new replies allowed.