-
-
-
-
- #include <iostream>
-
- #include <cstring>
- using namespace std;
-
- int main()
- {
-
-
-
-
-
- const char *c;
- string s = "1234";
- c = s.c_str();
- cout<<c<<endl;
- s = "abcde";
- cout<<c<<endl;
- }
结果是:
上面如果继续用c指针的话,导致的错误将是不可想象的。就如:1234变为abcd 其实上面的c = s.c_str(); 不是一个好习惯。既然c指针指向的内容容易失效,我们就应该按照上面的方法,那怎么把数据复制出来呢?这就要用到strcpy等函数(推荐)。
//更好的处理为: -
-
-
-
- #include <iostream>
-
- #include <cstring>
- using namespace std;
-
- int main()
- {
-
- char *c = new char[20];
- string s = "1234";
-
- strcpy(c,s.c_str());
- cout<<c<<endl;
- s = "abcd";
- cout<<c<<endl;
- }
|