我在一个更大的程序中遇到了问题,我制作了另一个较小的程序来显示问题.我期待输出
1 10
10 10
***************
2 10
10 10
****************
3 10
10 10
*****************
Run Code Online (Sandbox Code Playgroud)
...
但结果却不同.我在哪里弄错了?是因为它是const char*类型吗?我真的很困惑.
谢谢.
#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();
a[1] = to_string(b).c_str();
cout << a[0] << endl;
cout << a[1] << endl;
cout << "**************" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
Run Code Online (Sandbox Code Playgroud)
在这一行
a[0] = to_string(order).c_str();
Run Code Online (Sandbox Code Playgroud)
to_string(order)生成一个临时字符串.c_str()只要临时字符串存在,结果才有效,但临时字符串在语句后被销毁. a[0]然后留下一个无效的指针.
要解决此问题,您需要将字符串存储在某处,以免它们立即消失:
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |