【发布时间】:2020-11-26 15:37:56
【问题描述】:
以下代码给出了空字符串和长度 = 0,但在调试时我可以看到 childDisplayName 的名称正确。
CHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0; DWORD maxComponentLen = 0;
string childDisplayName = "";
DWORD fileSystemFlags = 0;
if (GetVolumeInformationA("C:\\", // L"\\MyServer\MyShare\"
(LPSTR)&childDisplayName, MAX_PATH+1,
&serialNumber, &maxComponentLen,
&fileSystemFlags, fileSystemName, sizeof(fileSystemName)) == true)
{
cout << childDisplayName << "length: "<<childDisplayName.length()<<endl;
}
以下代码可以正常工作。我不明白为什么 LPSTR 在传递 char 数组时有效,而在传递字符串时无效。
CHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0; DWORD maxComponentLen = 0;
CHAR childDisplayName[MAX_PATH + 1] = { 0 };
DWORD fileSystemFlags = 0;
if (GetVolumeInformationA("C:\\", // L"\\MyServer\MyShare\"
childDisplayName, MAX_PATH+1,
&serialNumber, &maxComponentLen,
&fileSystemFlags, fileSystemName, sizeof(fileSystemName)) == true)
{
cout << childDisplayName << "length: "<<strlen(childDisplayName)<<endl;
}
【问题讨论】:
-
字符串的地址不是字符的地址,
std::string只管理一个动态的字符数组。 -
@churill 感谢您的回复。但在第一个 sn-p 中,它打印空输出和长度 = 0。但是当我调试代码时,我可以在变量 childDisplayName 中看到正确的驱动器标签。你能解释一下吗?
-
每次转换都意味着,您正在回避 C++ 类型系统。结果是,编译器将不再验证正确性。验证正确性由您自己负责,但您没有这样做。
-
您好,如果任何答案对您有所帮助,请随时标记它以帮助遇到相同问题的人,如果您有任何问题,请告诉我。谢谢。
标签: c++ pointers winapi msdn lpstr