How can i populate an array of pointers, type char, in c++?

For example, lets have char *names[5] and I want to populate the array with for loop to make char *names[5] = {“Emanuel”, “Michael”, “John”, “George”, “Sam”}. How can I populate *names[5] using for loop and setw() function to limit the number of input characters. How to populate char *arr[n] with for loop, n - given integer.

You should avoid C-style char pointers and C-style arrays. Instead, prefer C+±style strings and C+±style vectors. Once you’ve done that…

vector<string> names;

for (auto nName = 0; nName < 5; ++nName) {
    string name;

    // Read name (max 4 chars long)
    cin >> setw(4) >> name;

    // Discard remaining input
1 Like

Thank yo Jeff_Mott, but I want to understand the pointer arithmetic. I don’t need to do any specific. And the task is to use for loop. One way I tried, is to make second char name[5] and to use strcpy(). When I put dimension of the array , for example char *names[5], setw(10), becomes meaningless, and I don’t know what to do.

Can you show what you’ve tried and describe where you’re stuck?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.