首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >[C++][ubuntu]C++如何将char*赋值给另一个char*

[C++][ubuntu]C++如何将char*赋值给另一个char*

作者头像
云未归来
发布2025-07-19 14:20:33
发布2025-07-19 14:20:33
970
举报

方法一:直接用=,在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; }

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-07-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档