当我像下面这样编写代码时,我正在使用C++在windows10上使用visual studio。
在调试模式下,在fop.fFrom被赋值为"C:\Users\C++.docx“后,奇怪的事情发生了,在cst = vrdir2.c_str() + '\0‘之后,fop.fFrom变成了"D:\vr”。我很困惑为什么会发生这种情况。
#include<iostream>
#include<io.h>
#include<time.h>
#include<stdlib.h>
#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
#include <sys/stat.h>
#include<direct.h>
#include<atlstr.h>
#pragma comment(lib, "shell32.lib")
using namespace std;
long long LAST_TIME_STAMP;
int main() {
string vrdir1 = "C:\\Users\\C++.docx";//version record dir
string vrdir2 = "D:\\vr";
SHFILEOPSTRUCT fop;//shell file opration struct
ZeroMemory(&fop, sizeof fop);
fop.wFunc = FO_COPY;
CString cst = vrdir1.c_str() + '\0';
cst.AppendChar(0);
fop.pFrom = cst;
cst = vrdir2.c_str() + '\0';
cst.AppendChar(0);
fop.pTo = cst;
}发布于 2021-06-17 22:04:50
pFrom是一个指针。它指向cst的内存。如果你改变cst,它也会改变pFrom。它类似于下面的场景:
int x = 5;
int *px = &x;
x = 10;px指向x的内存,如果你改变了x,这个改变也可以通过px看到。
在您的示例中,您可以简单地执行以下操作:
string vrdir1 = "C:\\Users\\C++.docx";//version record dir
string vrdir2 = "D:\\vr";
SHFILEOPSTRUCT fop;//shell file opration struct
ZeroMemory(&fop, sizeof fop);
fop.wFunc = FO_COPY;
fop.pFrom = vrdir1.c_str();
fop.pTo = vrdir2.c_str();而不使用CString。
作为一个建议,请不要混淆不同的字符串类型。选择一个,并坚持下去。
https://stackoverflow.com/questions/68015971
复制相似问题