仅列出四种,欢迎补充!
方法一:直接 “char* buf1=char* buf2” ,(!!!这里的赋值是将buf2的地址赋给了buf1,此后buf2的值改变,buf1也会变,因为buf1此时地址已经指向了buf2的地址!!!)
#include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
char* buf1="hello";
char* buf2=buf1;
std::cout<<bb<<std::endl;
return 0;
}
方法二:strcpy
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
char* buf1="hello";
char* buf2;
buf2=new char[6];//注意设置5报错,要算\0
strcpy(buf2,buf1);
std::cout<<buf2<<std::endl;
delete[] buf2;
return 0;
}
需要知道char*长度,delete防止内存泄漏
方法三:memcpy
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
char* buf1="hello";
char* buf2;
buf2=new char[5];
memcpy(buf2,buf1,5); //测试发现设置5也行
std::cout<<buf2<<std::endl;
delete[] buf2;
return 0;
}
需要知道数据长度
方法四:sprintf
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
char* buf1="hello";
char* buf2;
buf2=new char[6];
sprintf(buf2,"%s",buf1);
std::cout<<buf2<<std::endl;
delete[] buf2;
return 0;
}
版权声明:本文为xiaoqixiaoguai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。