
[英]arg of type “const char *” is incompatible with parameter of type “LPSTR” c++
[英]Why can I pass CHAR[] as a LPSTR parameter?
这对我有用...
std::string GetProgramDataPath() {
CHAR path[MAX_PATH];
HRESULT hr = SHGetFolderPathA(nullptr, CSIDL_COMMON_APPDATA, nullptr, 0, path); // path accepted as LPSTR parameter?
if (SUCCEEDED(hr)) {
return std::string(path); // then automatically cast to const char*?
}
else {
return std::string();
}
}
......但我不知道为什么。 我尝试通过LPSTR
,但我得到:
错误 C4700“使用了未初始化的局部变量‘路径’”
我查看了如何初始化LPSTR
并得出以下结论:
std::string GetProgramDataPath() {
LPSTR path = new CHAR[MAX_PATH];
HRESULT hr = SHGetFolderPathA(nullptr, CSIDL_COMMON_APPDATA, nullptr, 0, path);
if (SUCCEEDED(hr)) {
std::string strPath(path);
delete[] path;
return std::string(strPath);
}
else {
delete[] path;
return std::string();
}
}
这是“正确”的代码吗? 使用new
和delete
似乎是错误的。 我是否仅使用CHAR[]
做一些不安全的事情? 为什么它能代替LPSTR
工作? 我相信它与 C 中的“指针和数组的等价性”有关,但似乎在这段代码中有一些从CHAR[]
到LPSTR
到const char *
的自动转换我不明白。
我没有使用new
和delete
来管理 memory,而是使用std::string
并让它管理 memory。
static std::string GetProgramDataPath()
{
std::string buffer(MAX_PATH, '\0');
const HRESULT result = SHGetFolderPathA
(
nullptr,
CSIDL_COMMON_APPDATA,
nullptr,
0,
buffer.data()
);
if (SUCCEEDED(result))
{
// Cut off the trailing null terminating characters.
// Doing this will allow you to append to the string
// in the position that you'd expect.
if (const auto pos{ buffer.find_first_of('\0') }; pos != std::string::npos)
buffer.resize(pos);
// Here is how you can append to the string further.
buffer.append(R"(\Some\Other\Directory)");
return buffer;
}
buffer.clear();
return buffer;
}
这对我有用......但我不知道为什么。
LPSTR
只是CHAR*
的别名(又名char*
):
typedef CHAR *LPSTR;
在某些情况下,固定大小的CHAR[]
(又名char[]
)数组将衰减为指向其第一个元素的CHAR*
(又名char*
)指针,例如在 function 参数中按值传递数组时,就像您是做。
我尝试通过
LPSTR
,但出现Error C4700 "uninitialized local variable 'path' used"
。
因为LPSTR
只是一个指针,您可能没有将它指向任何有意义的地方。
这是“正确”的代码吗?
从技术上讲是的,这将起作用(尽管return std::string(strPath)
应该改为return strPath
)。 但是,您应该考虑使用std::string
或std::vector<char>
来为您管理 memory,不要直接使用new[]
/ delete[]
,例如:
std::string GetProgramDataPath() {
std::vector<char> path(MAX_PATH);
HRESULT hr = SHGetFolderPathA(nullptr, CSIDL_COMMON_APPDATA, nullptr, 0, path.data());
if (SUCCEEDED(hr)) {
return std::string(path.data());
}
return std::string();
}
我是否仅使用
CHAR[]
做一些不安全的事情?
不。
为什么它能代替
LPSTR
工作?
因为CHAR[]
衰减为LPSTR
是其别名的同一类型。
这段代码中似乎有一些从
CHAR[]
到LPSTR
到const char *
的自动转换。
正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.