先看看代买:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str = "hello world";
const char *s = str.c_str();
printf("s = %s\n",s);
str = "Hello World!";
printf("s = %s\n",s);
system("pause");
return 0;
}
输出结果:
s = hello world
s = Hello World!
发现当执行 const char *s = str.c_str();以后,再修改str的值,s的值也会被更改。修改了str之后,s取得的数据就是垃圾数据。跟预期的值不一样。
究其原因是因为c_str()函数返回的是一个指针,指向的是字符串str的首地址。所以当str改变的时候,指针指向内容也就随之变化。
那用什么方法能够避免这种错误呢?
看:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str = "hello world";
char s[20];
strncpy(s, str.c_str(), strlen(str.c_str()) + 1);
printf("s = %s\n", s);
str = "HELLO WORLD";
printf("s = %s\n", s);
system("pause");
return 0;
}
运行结果:
s = hello world
s = hello world
通过strcpy或者strncpy都可以有效的解决 产生垃圾数据的问题。