方法一:直接用=,在ubuntu上测试通过,windows好像不行,代码如下:
#include <iostream> #include <unistd.h> using namespace std; int main(int argc, char *argv[]) { char* aa="hello"; char* bb=aa; std::cout<<bb<<std::endl; return 0; } 方法二:使用strcpy,代码如下:
#include <iostream> #include <unistd.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { char* aa="hello"; char* bb; bb=new char[6];//注意设置5报错,要算\0 strcpy(bb,aa); std::cout<<bb<<std::endl; delete[] bb; return 0; } 点评:这种方法需要知道原char*长度,而且需要delete防止内存泄漏
方法三:使用memcpy,代码如下:
#include <iostream> #include <unistd.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { char* aa="hello"; char* bb; bb=new char[5]; memcpy(bb,aa,5);//测试发现设置5也行 std::cout<<bb<<std::endl; delete[] bb; return 0; }
点评:这种方法需要知道原char*长度,而且需要delete防止内存泄漏
方法四:sprintf函数
#include <iostream> #include <unistd.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { char* aa="hello"; char* bb; bb=new char[6]; sprintf(bb,"%s",aa); std::cout<<bb<<std::endl; delete[] bb; return 0; }
方法五:循环遍历 #include <iostream> #include <unistd.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { char* aa="hello"; char* bb; bb=new char[6]; int i = 0; while (*aa != '\0') bb[i++] = *aa++; bb[i] = '\0'; //添加结束符 std::cout<<bb<<std::endl; delete[] bb; return 0; }