when i use a dynamic 2d char array using pointers, i dont get any errors but the program is not executed correctly...


//Pro to enter and display strings using dynamic 2d char array.

#include<iostream.h>
#include<conio.h>
void main()
{
char **v;
int s;
cout<<"Enter size :: ";
cin>>s;
v=new char[s];
cout<<"\nEnter "<<s<<" strings :: \n";
for(int i=0;i<s;i++)
cin>>v[i];
cout<<"The strings u entered are :: \n ";
for(i=0;i<s;i++)
cout<<v[i]<<"\n";
getch();
}

When I do that I get all the strings displayed except v[2]...ie 3rd string.I did it in primitive borlad compiler turbo c++ v3.0......When I do it in turbo c++ 5.0, the system does not allows it to run cause the program overloads the processor!! I would be pleased to get answer from u friends ...

If you have a 2D array, you're going to have to allocate 2 dimensions. I only see you allocating one dimension.

you haven't inputed a 2D array

char arr[20][20]

thats the syntax for a 2D array.

LOOP for cin is completely wrong.

for(i=0; i<r; i++) // row loop
                  {
                   for(j=0; j<c ;j++)//colum loop
                         {
                          cin>> a[i][j];
                           }
                   }

There is nothing wrong with the original input loop. These are words/strings that the user is inputting, not integers or something like that, where a nested input loop would be required. If the array is supposed to be 20 x 20 like you mentioned in your example, you don't need or want 400 cin statements. You want 20. The user is entering in words/strings. What if he/she decides to enter 20 short words like "hat", "cat", etc.?

The problem is that the program is only allocating one character of memory per word, which isn't enough. This line:

v=new char[s];

declares that there are s characters. Instead it should declare that there are s strings. Like this:

v=new char*[s];

There still needs to be memory allocated for each of those s strings, but I think that's what Gopala Krishnan needs to do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.