2-D dynamic arrays
I was assigned a project that requires a 2-D dynamic array of char and I am having trouble finding the proper way to define it. It is supposed to hold people's names inputted by the user. The user is supposed to be able to input as many names as they want. From what I learned in class it is supposed to look something like this.
Is this code using dynamic arrays correctly? I am very confused in the getnames function that I wrote. I know what I have is wrong, but could someone please show me an example that would use the arrays correctly? That function is supposed to read in a name from the user and store it in one row of the dynamic array. And then if the user has another input it should run again and read in the next name and store it in the next line. Any help would be appreciated, Thanks.
char ** names;
getnames(names, length, k);
cout << "Are there any more names to input?1 = yes, 2 = no " << endl;
cin >> answer;
void getnames (char ** names, int& length, int&k)
char * temp = new char [length];
cout << "Enter the competitor's name: " << endl;
length = strlen(temp);
names[k] = new char[length];
First, I must ask if you can use C++ strings and vectors. This problem is so much easier if you use those.
If you cannot, then you need to figure out how big each dimension of the array will be. The first dimension depends on how many names will be input. In this case, you don't know how many names will be input because you keep inputting names until the user says stop. This will make using dynamic arrays very difficult, because you have to guess a number, and if it is too little you have to allocate a new array and copy everything over.
To make things simpler, pick a large number (maybe 100) and create an array of char*'s with that size. You can worry about resizing it later when you get the rest of the code working. The important thing is for you to figure out the syntax of creating an array of char* with a size of 100. Can you do that and post your attempt?
The array of char*'s is an array of names. Each time you enter a name, you get the length of that name and you can then allocate the char array based on that length. But you will have the same problem. In order to read in a name using character arrays, you need to guess a maximum length before hand.
This problem does not lend itself to dynamic arrays with new, are you sure that's what you're supposed to use? You can use C-style arrays with a maximum size and get the same effect, or C++ strings and vectors and have really dynamic containers. Using new with dynamic values for this means you have a lot of code to write.