C++ 字符串到非常量字符的转换*
我构建了一些C+阵列,如下所示:C++ 字符串到非常量字符的转换*,c++,C++,我构建了一些C+阵列,如下所示: std:array<const char *, 4) test1 = {abc.c_str(), def.c_str(), ghi.c_str()}; std:array这应该行得通 abc.append(1, 0); // guarantee NUL termination def.append(1, 0); ghi.append(1, 0); std:array<char *, 4> test1 = {abc.data(), def.da
std:array<const char *, 4) test1 = {abc.c_str(), def.c_str(), ghi.c_str()};
std:array这应该行得通
abc.append(1, 0); // guarantee NUL termination
def.append(1, 0);
ghi.append(1, 0);
std:array<char *, 4> test1 = {abc.data(), def.data(), ghi.data()};
abc.append(1,0);//无担保终止
def.append(1,0);
ghi.append(1,0);
std:array test1={abc.data(),def.data(),ghi.data()};
或
abc.append(1,0);
def.append(1,0);
ghi.append(1,0);
std:array test1={&abc[0],&def[0],&ghi[0]};
这应该行得通
abc.append(1, 0); // guarantee NUL termination
def.append(1, 0);
ghi.append(1, 0);
std:array<char *, 4> test1 = {abc.data(), def.data(), ghi.data()};
abc.append(1,0);//无担保终止
def.append(1,0);
ghi.append(1,0);
std:array test1={abc.data(),def.data(),ghi.data()};
或
abc.append(1,0);
def.append(1,0);
ghi.append(1,0);
std:array test1={&abc[0],&def[0],&ghi[0]};
如果函数可能会修改字符串,则应将字符串大小调整为函数可能使用的最大大小,然后在返回时再次调整大小
abc.resize(max);
DoSomething(&abc[0]);
abc.resize(strlen(&abc[0]));
如果您知道函数没有修改字符串,那么函数原型就是在欺骗您。你可以躺下:
DoSomething(const_cast<char *>(abc.c_str()));
DoSomething(const_cast(abc.c_str());
如果函数可能会修改字符串,则应将字符串大小调整为函数可能使用的最大大小,然后在返回时再次调整大小
abc.resize(max);
DoSomething(&abc[0]);
abc.resize(strlen(&abc[0]));
如果您知道函数没有修改字符串,那么函数原型就是在欺骗您。你可以躺下:
DoSomething(const_cast<char *>(abc.c_str()));
DoSomething(const_cast(abc.c_str());
+strdup()
/free()
以防原型函数修改字符串。如果你不介意我问的话,abc.c_str()有什么意义代码>等等?它有什么副作用?@chris:它确保字符串内容后面跟一个NUL字节。@Alex:std::string
不是不可变的。+strdup()
/free()
以防原型函数修改字符串。如果你不介意我问你,abc.c_str()有什么意义代码>等等?它有什么副作用?@chris:它确保字符串内容后面跟一个NUL字节。@Alex:std::string
不是不可变的。人渣函数原型。这确实是我所知道的唯一合理的用途:弥补别人的错误。调整字符串大小也很好。一个main
-风格的函数不能增加作为参数传入的字符串的长度,即使它确实修改了字符串(例如,它可以使用strtok
)@BenVoigt,一个main
-风格的函数不会接收string
s,它会接收char*
s。我想如果你知道字符串长度不会改变,你可以省去一对resize
。@harper:你打算把那条评论指向Mark吗?@BenVoigt,因为这是我的答案,所以我会得到通知。与main
的比较并没有改变我的答案。人渣功能原型。这确实是我所知道的唯一合理的用途:弥补别人的错误。调整字符串大小也很好。一个main
-风格的函数不能增加作为参数传入的字符串的长度,即使它确实修改了字符串(例如,它可以使用strtok
)@BenVoigt,一个main
-风格的函数不会接收string
s,它会接收char*
s。我想如果你知道字符串长度不会改变,你可以省去一对resize
。@harper:你打算把那条评论指向Mark吗?@BenVoigt,因为这是我的答案,所以我会得到通知。与main
的比较不会改变我的答案。