Click to See Complete Forum and Search --> : double pointer problem..


never9
June 3rd, 1999, 08:30 PM
#include <iostream.h>
void main()
{
char **pp = new char*[10];
char *p[10];
for(int i=0; i<10; i++)
p[i] = new char[10];
p[0] = "This";
p[1] = " is";
p[2] = " a";
p[3] = " test";
p[4] = " version.";
p[5] = " You";
p[6] = "know?";
p[7] = " I";
p[8] = " love";
p[9] = " you..";
for(i=0; i<10; i++)
{
pp[i] = p[i];
cout << pp[i] << endl;
}

for(i=0; i<10; i++)
delete [] pp[i]; // <== Here is the problem
delete [] pp;
}

This is my test version of double pointer.
Almost everything is executed well.
But the execution is halted in the arrow marked
position.
Could you give me a solution to this problem.
I programmed this source in Visual C++ 6.0.
I can't understand the fact that
when I execute this source in Debug mode,
the execution is halted but in Release mode,
it's OK.
Need your help

June 3rd, 1999, 09:22 PM
There appears to be more than one problem with that source.

1) although you declare

char *p[10];

you then use

p = new char[10]; // in your contest you are creating
// 10, 10 char arrays and assigning
// each array the same address effectively
// overwriting the previous on

I think what you actually meant to say was

p[i] = (char *)new char[10];

2. you use

p[0] = "This";

and you actually intend

strcpy(p[0],"This");

3. In your delete loop you are actually delete pp 10 times?
You allocate it once, and should only delete it once. So this loop
should look something like

for (int i = 0; i < 10 ; i++)
{
delete [] p[i];
}
delete [] pp;


Look at this source and see if isn't closer to way you intend
#include <string.h>
#include <iostream.h>

char *samples[] =
{
{ "This" },
{ "is" },
{ "a" },
{ "test" }
};

void main()
{
char **pp = new char * [4];
for(int i=0; i<4; i++)
{
pp[i] = (char*)new char[10];
strcpy(pp[i],samples[i]);
}


for(i=0; i<4; i++)
delete [] pp[i] ;
delete [] pp;
}

Radman
June 3rd, 1999, 11:23 PM
Hey, i'm not used to all this pointer stuff, even though i use them alot,...

Whats the delete []pp;

mean???

Word,
Ryan "Radman" Du Bois

David Langis
June 3rd, 1999, 11:57 PM
It should be a good idea to use j for counters instead of i as i between brackets is the tag for putting text in italic.

June 4th, 1999, 07:52 AM
delete the array pp;