Reputation: 496
The following code prints the expected output within the for loop , but once I exit the loop , it only prints "Here" , with nothing underneath it. What am I missing here?
char ** strs = new char*[n];
for (int i = 0; i < n; i++)
{
string str;
getline(cin, str);
strs[i] = const_cast<char*>(str.c_str());
cout << strs[i] << endl;
}
cout <<"here" <<strs[1] << endl;
Upvotes: 1
Views: 184
Reputation: 206567
What am I missing here?
In theory, you are seeing the symptoms of undefined behavior.
You are storing the a pointer to the data held by str
in strs[i]
but str
is deleted when you get out of the for
loop. The pointer is not valid after the end of the loop.
In practice, you are seeing only the last value read since every element of strs
stores the same pointer value.
You can avoid problems by using standard containers.
std::vector<std::string>> strs;
for (int i = 0; i < n; i++)
{
string str;
getline(cin, str);
strs.push_back(str);
cout << strs[i] << endl;
}
Upvotes: 4
Reputation: 385098
Your pointers are dangling.
You've stored pointers to the data buffer of a std::string
. That buffer ceases to exist on each new iteration, to be replaced by the buffer of the next iteration's version of str
; furthermore, there is absolutely no trace of it after the loop ends.
Don't do this. Just store std::string
s.
That const_cast
is completely ill-advised too. Not sure why you're doing it.
Upvotes: 6