deleting array of pointers
Apr 26, 2009 at 5:54pm UTC
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 Apr 26, 2009 at 5:56pm UTC
Apr 26, 2009 at 6:12pm UTC
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:
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 Apr 26, 2009 at 6:13pm UTC
Apr 26, 2009 at 7:50pm UTC
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?
Apr 26, 2009 at 7:54pm UTC
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:
games1[i]
will then be the same 'Goal' object as
games[i]
Last edited on Apr 26, 2009 at 7:55pm UTC
Apr 26, 2009 at 7:55pm UTC
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
Apr 26, 2009 at 8:02pm UTC
Thanks guys, very helpfull!!
Topic archived. No new replies allowed.