I am trying to make dynamic array of char arrays
const int nameLength = 10;
int dataCount = 5;
// Initialize array of char array
char ** name;
name = new char*[dataCount];
for (int i = 0; i < dataCount; i++)
name[i] = new char[nameLength];
// Prompt for names
for (int i = 0; i < dataCount; i++) {
char userInput[nameLength];
cout << "Input data " << i << " :";
cin >> userInput;
name[i] = userInput;
}
cout << endl;
// Display data entered
for (int i = 0; i < dataCount; i++) {
cout << "Name" << i << " : " << name[i] << endl;
}
But the output is wrong:
Input data 0 :abcde
Input data 1 :fghij
Input data 2 :klmno
Input data 3 :pqrst
Input data 4 :uvwxy
Name0 : uvwxy
Name1 : uvwxy
Name2 : uvwxy
Name3 : uvwxy
Name4 : uvwxy
If I change the input part to this then it would work as expected:
cin >> name[i];
But in my case I cannot directly enter the data to the variable like that.
Can anyone explain what's wrong with the code? I searched everywhere but it doesn't seems to help
strcpythen. Or better yetstd::vector<std::string>. Why can't you use the last code snippet?std::stringthan C-style arrays of characters. Prefer to usestd::vectorrather than dynamically allocated arrays.