深层复制std :: string :: c_str()to char * [英] Deep copy std::string::c_str() to char *
本文介绍了深层复制std :: string :: c_str()to char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有一个复杂的功能,我和我们的团队不想重构利用std :: string,它需要一个char *被修改。我如何正确地做一个深度复制的字符串:: c_str()成一个char *?我不要修改字符串的内部存储的char *。
Currently I have a complex function that myself and our team are not wanting to refactor to utilize std::string and it takes a char* which is modified. How would I properly make a deep-copy of string::c_str() into a char*? I am not looking to modify the string's internally stored char*.
char *cstr = string.c_str();
失败,因为c_str()是const。
fails because c_str() is const.
推荐答案
你可以这样做:
const std::string::size_type size = string.size();
char *buffer = new char[size + 1]; //we need extra char for NUL
memcpy(buffer, string.c_str(), size + 1);
这篇关于深层复制std :: string :: c_str()to char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文