Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer to pointer problems

Status
Not open for further replies.

stuartd

Programmer
Jan 8, 2001
146
US
Hi,

I am trying to get a sizeable multi dimension array using char **

ie
main()
{
char **data;

data[0]=new char[6];
strcpy(data[0],"Hello");
data[1]=new char[6];
strcpy(data[1],"World");

int x;
while(data[x] !=NULL)
{
printf("%s\n",data[x]); x++;
}
}

This causes a segmentation fault. What an i doing wrong?
 
You aren't allocating memory for pointer data. data[0] doesn't exist. You should do:
Code:
main()
{
   char **data;

   data=new *char[8] //This way you'll have 8 pointers.
   //You can also do data=malloc(8*sizeof(char*)).

   data[0]=new char[6];
   strcpy(data[0],"Hello");
   data[1]=new char[6];
   strcpy(data[1],"World");              

   int x=0;
   while(x<8 && data[x]!=NULL)
   {                
      printf(&quot;%s\n&quot;,data[x]); x++;          
   }
}
And you're supposing that compiler initializes those pointers (data[x]) to NULL. This can be false.
 
Thanks - that is exactly what I want to do.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top