Well, today; I’ve come across a strange little situation with e.g. char* cFileCopy = strDrive; _
This should make cFileCopy hold the value of strDrive only at this point, which it does, however when I use strcat(cFileCopy, cFileName);
the value of strDrive also changes to the value of cFileCopy after strcat()
_
I’m not sure what’s happening, but here’s the code if anybody could shed a little light on the situation.
DWORD dwDrives = GetLogicalDrives();
char strDrive[3];
for(int i = 0; i<26; i++)
{
wsprintf(strDrive, "%c:\\", 'A'+i);
if(GetDriveType(strDrive) == DRIVE_REMOVABLE)
{
char* cFileName = new char[11];
cFileName = "test.txt";
char* cFileCopy = strDrive;
strcat(cFileCopy, cFileName);
MessageBox(NULL, strDrive, "Strange", MB_OK); //MSG - This shows drive:\test.txt when it should show only drive:\/
MessageBox(NULL, cFileCopy, "OK", MB_OK); //MSG - This should be showing drive:\test.txt, which it does.
}
}
Any help is appreciated, Thank you.
You need to revisit how pointers work – if you point two variables to the same memory (as here), then a modification to the memory pointed to by one will also change the value pointedd to by the other.
Note that you are also overflowing the 3 byte
strDrivebuffer handily in thatstrcatcall, which will result in obscure bugs surfacing down the line. There is also a leak ofcFileNamewhich has nodelete[]call to match thenew[](use smart pointers orstd::stringinstead to simplify this).If you want the semantics you expect, you should be using C++
std::string, not raw pointers.