hoshiKuzu
hoshiKuzu

Reputation: 915

List of arrays/pointers c++

I am inputting char arrays into a list. This is what i have so far

list<char*> l; 
char str[50];

cout<<"Enter strings. 0 to stop:\n";
while(1)
{
    cin >> str;
    if(strcmp(str, "0") == 0)
        break;

    l.push_back(str);
}

list<char*>::iterator p;

// display
for(p = l.begin() ; p != l.end(); p++)
    cout<<*p<<endl;

The display loop displays only the last entered string n times. Is there a better way to represent a list of arrays?

Upvotes: 0

Views: 74

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The problem is that you always point to the same buffer str: if you want your list to contain different values, you'll need a different buffer for each entry. Of course, this quickly becomes hard to manage. Thus, you are much better off storing std::string objects in our list:

std::list<std::string> l;
for (std::string tmp; std::cin >> tmp; ) {
    if (tmp == "0") {
        break;
    }
    l.push_back(tmp);
}

Note that using std::cin >> str; as you do it is also highly dangerous: there is nothing which prevents the input from overflowing the buffer! If you use an input operator with a char buffer, make sure you set the stream's width() to the size of the buffer before doing so (std::setw() is declared in <iomanip>):

if (std::cin >> std::setw(sizeof(str)) >> str) {
    // ...
}

And, of course, you should check after each input that it was, indeed, successful.

Upvotes: 1

John3136
John3136

Reputation: 29265

It's doing exactly what you asked it to! Your list is an array of char* and you give it the same address every time. What is located at that address changes each time through the loop...

...And don't even think about returning that list from a function. The address in the list is only valid in the scope of the function call.

You'd be better off with something like std::list<std::string>

Upvotes: 3

Related Questions