Karol Borkowski
Karol Borkowski

Reputation: 742

ostringstream gets wrong int value after incrementation [c++]

This is part of my code:

for(int i=0; i<10; i++)
{
    tab[i]=new char[80];
    oss.str("");
    oss<<"line number: <<i;
    temp=oss.str();
    tab[i]=(char*)temp.c_str();
}

and when I print the tab, the result is in turns 8 and 9. Am I doing something wrong?

Upvotes: 0

Views: 118

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54355

Taking a bunch of comments and consolidating (Why are you commentators not answering instead?):

What you are actually doing there is changing the pointer value of tab[i] from your allocated memory to the internal string of temp. Which is a bad idea because temp will free that memory as soon as it is destructed.

You don't need temp at all, as far as I can see.

The C way to fix this is to use strcpy(tab[i], oss.str().c_str()) which will copy the characters one by one. Note that your current code does a new char[80] so if your string is longer than 79 characters it will overflow. If you must use a new'd buffer, do it with something like new char[oss.str().size() + 1]

The C++ way to fix this is to use an array of std::string instead of an array of char*. Then you could just assign, like tab[i] = oss.str() and it would copy it properly. It would also clean up the memory used when the array goes out of scope, as your code right now doesn't do.

Upvotes: 2

Related Questions