c++ string.c_str()转const char*的一个坑点

匿名 (未验证) 提交于 2019-12-02 23:34:01
版权声明:咸鱼一只。种树的最好时间是十年前,其次是现在。 https://blog.csdn.net/yxpandjay/article/details/90289095

如果你想以string的内容作为返回值,而又必须返回char*型时

 #错误示范 #因为string这个类在函数结束时就调用析构函数了,导致返回的result指向一个已经释放的地址  char* TestFun(){     string test_string = "广东佛山机会开io";     const char* result = test_string.c_str();     return result; }    #正确示范  char* TestFun(){     string test_string = "广东佛山机会开io";     const char* result = test_string.c_str(); 	int tail = 0; 	while (result[tail] != '\0') { 		tail++; 	} 	char* real_result = (char*)malloc(tail+1); 	for (int i = 0; i <= tail; i++) { 		real_result[i] = result[i]; 	} 		return real_result; }

文章来源: https://blog.csdn.net/yxpandjay/article/details/90289095
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!