Victor Volpe
Victor Volpe

Reputation: 111

C++ pointer trick

I'm trying to understand how this C++ pointer trick really works. In MSDN Obtaining a File Name From a File Handle we can see:

// Copy the drive letter to the template string
*szDrive = *p;

At the first they declare an "template string" that will receive the drive letter without the trailing backslash (TCHAR szDrive[3] = TEXT(" :");) and then they do this pointer trick and voilà! I've tryied to disasembly but no clue at all:

            *szDrive = *p;
011D178D  mov         eax,dword ptr [p]  
011D1793  mov         cl,byte ptr [eax]  
011D1795  mov         byte ptr [ebp-214h],cl

I'm afraid that is the lamest trick ever...

Upvotes: 2

Views: 270

Answers (2)

Slava
Slava

Reputation: 44258

This code:

*szDrive = *p;

is equivalent to:

szDrive[0] = p[0];

which means you copy first symbol from string p to string szDrive, which is drive letter in this case.

Upvotes: 8

Jeremy Friesner
Jeremy Friesner

Reputation: 73081

Since in C++ char-arrays and char-pointers are in many ways equivalent, they are dereferencing both pointers to copy one element from one array to the other.

You could equivalently express the same functionality like this, which might make it easier to understand what they are doing:

szDrive[0] = p[0];

Upvotes: 10

Related Questions