0

I know my question is not specific but let me explain it this code

char name[5][30];
for (int i = 0; i < 5; i++)
    cin >> name[i];

for (int i = 0; i < 5; i++)
    cout<<name[i];

in the example above i created an array of characters where you can input five words each with 30 bit length. and it works just fine but when i try to use a pointer like so when you don't know how many words you are about to input. I get an error in line 5 saying a value of type int cant be asigned to char and i understand the error but how how to get pass this problem?

int n;
cout << "Number of names" << endl;
cin >> n;
int *name;
name = new char[n][30];
for (int i = 0; i < 5; i++){
    cin >> *name;
    name++;

}

for (int i = 0; i < 5; i++){
    cout << *name;
    name++;
}
17
  • 4
    How exactly do you expect an uninitialized name to automatically point to your new-ed array? Commented Nov 17, 2016 at 13:35
  • 3
    std::vector<int> and std::string. Commented Nov 17, 2016 at 13:35
  • 1
    Is there any reason why you don't want to use std::vector (variable-length array) and std::string? Commented Nov 17, 2016 at 13:38
  • 2
    Why is name an int* in the second example? IIn what way does it make sense for a name to be an int? Commented Nov 17, 2016 at 13:39
  • 2
    As a C++ novice you should learn about std::vector and std::string first, and about pointers and new forty seventh. Commented Nov 17, 2016 at 13:45

1 Answer 1

3
  • Use char, not int.
  • Incrementing name doesn't seem good idea because it have to be returned to the first element before printing. I used array indexing operator.
  • I guess n input & output should be done instead of fixed 5 input & output.
    int n;
    cout << "Number of names" << endl;
    cin >> n;
    char (*name)[30];
    name = new char[n][30];
    for (int i = 0; i < n; i++){
        cin >> name[i];

    }

    for (int i = 0; i < n; i++){
        cout << name[i];
    }
    delete[] name;
Sign up to request clarification or add additional context in comments.

3 Comments

you didn't free memory
@Raindrop7 What I posted is not all of the program. I didn't, but it may be freed later.
@MikeCAT: I know that. but the op may continue using it unknowing the potential danger of memory leak

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.