2

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

3
  • 1
    Use strcpy then. Or better yet std::vector<std::string>. Why can't you use the last code snippet? Commented Oct 25, 2016 at 21:45
  • 3
    Prefer to use std::string than C-style arrays of characters. Prefer to use std::vector rather than dynamically allocated arrays. Commented Oct 25, 2016 at 21:46
  • Actually the char array is in a class and i need a function to input the char array Commented Oct 25, 2016 at 21:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

is there a way to copy it without STL?
You can do a copy by hand if you like. Something like for(int j = 0; j < nameLength; ++j) name[i][j] = userInput[j].
By the way, strcpy is not necessarily in STL, it's just a C function.
strcpy works just like I what I needed. At first i think i need to change all my char arrays to string to use it. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.