您的位置:首页 > 其它

std::string 转换为 const* char

2013-04-18 11:12 363 查看
std::string 转换为 const* char,方式如下:

std::string str;

const char * c = str.c_str();

如果需要转换为一个可变char,做法如下:

std::string str;

char * writable = new char[str.size() + 1];

std::copy(str.begin(), str.end(), writable);

writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it

delete[] writable;

需要说明的是,上面的这个方法并不是非常安全,在新的调用和被删除之前有可能会导致内存泄露。解决的方法有两个,使用boost::scoped_array或者std::vector采用copy的方式进行重新构建。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: