版权声明:咸鱼一只。种树的最好时间是十年前,其次是现在。 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