#include<iostream> #include<string> #include<cstring> using namespace std; int main(){ /* 定义一个const char* 然后将其转化为一个char* */ const char *strs = "test_string"; string tempStrs(strs); // strs转换为string char *dstStrs = const_cast<char*>(tempStrs.c_str()); // 再将string转换char*类型 printf("dstStrs: %s\n", dstStrs); /* 使用一个char* 为另外一个char* 赋值 */ char* src_strs = "Iam src_strs"; // C++中不建议这种char*的直接指向一个字符串,但是c中却可以 char* dst_strs_ptr = NULL; dst_strs_ptr = src_strs; // 不建议这种char*的直接赋值操作,因为两者指向的地址完全 // 相同,当src_strs内容被修改时,dst_strs的也会被修改 cout <<static_cast<void *>(src_strs) << endl; cout <<static_cast<void *>(dst_strs_ptr) << endl; cout << " " << endl; // 赋值方式一:转给string后再转为char* std::string tempStrsPtr(src_strs); dst_strs_ptr = const_cast<char*>(tempStrsPtr.c_str()); cout <<static_cast<void *>(src_strs) << endl; cout <<static_cast<void *>(dst_strs_ptr) << endl; // 这种赋值方式为dst_strs_ptr单独开辟了一块地址空间 cout << "dst_strs_ptr is: " << dst_strs_ptr << endl; // 赋值方式二:使用strncpy或者strcpy strcpy(dst_strs_ptr, src_strs); cout <<static_cast<void *>(src_strs) << endl; cout <<static_cast<void *>(dst_strs_ptr) << endl; // cout << "dst_strs_ptr is: " << dst_strs_ptr << endl; strncpy(dst_strs_ptr, src_strs, strlen(src_strs)+1); cout <<static_cast<void *>(src_strs) << endl; cout <<static_cast<void *>(dst_strs_ptr) << endl; // cout << "dst_strs_ptr is: " << dst_strs_ptr << endl; cout << " " << endl; /* 使用char* 为char[] 赋值 */ char* src_strs_2 = "data"; char dst_strs_arr[] = "temp"; cout << &dst_strs_arr << endl; // dst_strs_arr = src_strs_2; // char*转char[]是无法直接用=赋值的 strncpy(dst_strs_arr, src_strs_2, strlen(src_strs_2)+1); cout << dst_strs_arr << endl; return 0; }
(1) 不可以直接使用char* 对char* 赋值
char *s1 = "NULL"; char *s2 = s1; // s1和s2指向同一个地址,当s1指向的内容发生改变时,s2可能也会改变
正确的做法如下
char *src = "test"; char *dst = NULL; // 方法一:使用stncpy