c++ - 类型 "const char **"的参数与类型 "const char *"的参数不兼容

标签 c++

我在这段代码中遇到了这个错误:

string folder;
getline(cin, folder);

string folder2 = folder + "/index.txt";
const char* oldhtml[] = { folder2.c_str() };
folder2 = folder + "/index.html";
const char* newhtml[] = { folder2.c_str()};
rename(oldhtml, newhtml);

错误发生在:rename(oldhtml, newhtml);

我是 C++ 的新手。因此,如果这是一个简单的修复,我深表歉意

最佳答案

看来你不明白这一行:

const char* oldhtml[] = { folder2.c_str() };

这声明了一个长度为 1 的数组。数组元素是一个指针,用 folder2.c_str() 的结果初始化(可能指向字符串的内部存储)。

然而,您随后在下一行更改了 folder2。这会使之前对 c_str 的任何调用的结果无效,因此 oldhtml[0] 现在是一个悬空指针。

写这段代码更好的方法是一路使用string:

string oldhtml = folder + "/index.txt";
string newhtml = folder + "/index.html";
rename(oldhtml.c_str(), newhtml.c_str());

关于c++ - 类型 "const char **"的参数与类型 "const char *"的参数不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31317619/

相关文章:

c++ - 引起问题的纹理

c++ - DataContractSerialize 错误

c++ - 类型名和范围运算符的语法错误

c++ - boost::指针与值的任何混淆

c++ - 当 InProcServer32 键定义 DLL 的完整路径时,为什么 PATH 环境变量中需要 COM DLL 的路径?

c++ - 为什么将对象引用参数传递给线程函数无法编译?

c++ - 为什么 g++ 不生成 "raw"符号?

c++ - 是否可以替换/或 .在宏中带有 __ 的字符串中?

c++ - 如何命名 C++ 捕获变量?

C++ DLL插件接口(interface)