简体   繁体   中英

Weird output when using const char*, to_string() and c_str()

I have a program that uses to_string to convert an int to a string , then converts that to a C string using string::c_str() , which is stored in an array of const char* . When the program outputs each const char* , the results are not what I unexpected. For the sample program below, which outputs a counter and an unchanging variable, I expected the output to consist of the counter, followed by an unchanging amount, then asterisks to separate:

 1 
10 
*************** 
2 
10 
**************** 
3 
10 
***************** 
 

Instead of the count up, each loop iteration always outputs the same value (which happens to be the value of the unchanging variable):

 10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 
10 
10 
************** 

The sample program used to produce the above:

#include <iostream>
#include <string>
using namespace std;
int main() {
    int order = 1;
    for (int i = 1; i < 10; ++i, ++order) {
        const char* a[2];
        int b = 10;
        a[0] = to_string(order).c_str(); // these
        a[1] = to_string(b).c_str();     // are the
        cout << a[0] << endl;            // relevant
        cout << a[1] << endl;            // lines
        cout << "**************" << endl;
    }
}

Where is the mistake? Is it because the array elements have const char * type?

In this line

a[0] = to_string(order).c_str();

to_string(order) generates a temporary string. The result of c_str() is only valid as long as the temporary string exists, but the temporary string is destroyed after the statement. a[0] is then left holding an invalid pointer.

To work around this, you'll need to store the strings somewhere so they don't go away immediately:

#include<iostream>
#include<string>
using namespace std;
int main()
{
        int order=1;
        for(int i=1; i<10;++i,++order){
                const char* a[2];
                int b = 10;
                auto order_str = to_string(order);
                auto b_str = to_string(b);
                a[0] = order_str.c_str();
                a[1] = b_str.c_str();
                cout << a[0] << endl;
                cout << a[1] << endl;
                cout << "**************" << endl;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM