wthe22
wthe22

Reputation: 77

C++ Dynamic array of char arrays

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

Upvotes: 2

Views: 17310

Answers (1)

grigor
grigor

Reputation: 1624

You are just copying pointers, not strings. So in fact all of your name[i] will be equal to userInput, and remember that they are both pointers. If you want to copy the full string you should use strcpy for example.

Since you're copying pointers, all of them point to the same string and show whatever was your last input.

Upvotes: 3

Related Questions