feos
feos

Reputation: 1116

Accessing struct members by a pointer

I have a multi-instance dialog, whose HWND and DC are contained in a vector of structs. Before I call CreateWindowEx(), I allocate memory for a new instance of the struct and pass its pointer to WndProc (with lpParam).

Inside the WndProc I have the following code:

HexParams Hex;
HexParams *pHex;
if (uMsg == WM_NCCREATE) {
    SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT *)lParam)->lpCreateParams);
    return TRUE;
} else {
    LONG_PTR lpUserData = GetWindowLongPtr(hDlg, GWLP_USERDATA);
    if (lpUserData) {
        pHex = (HexParams *)lpUserData;
        Hex = *pHex;
    } else
        return DefWindowProc(hDlg, uMsg, wParam, lParam);
}

Then throughout the whole WndProc I'm constantly using Hex.Member to acces its memebrs, read from them and write to them (if was left from when it was a single instance and the struct was global). So when I was adding multi-instance support, I hoped that simply dereferencing the pointer would give me the struct memebrs from that vector.

However, the following examples do different things:

Hex.DC = GetDC(hDlg);
pHex->DC = GetDC(hDlg);

Despite of doing Hex = *pHex; before it. pHex->DC writes to my vector element, but Hex.DC writes to somewhere I can't figure out. Is there a way to preserve Hex.Member usage in the code, or I'll have to convert them all to pHex->Member?

I may be "missing the point of pointers", but I can't get how to properly use them here.

Upvotes: 0

Views: 181

Answers (1)

JDługosz
JDługosz

Reputation: 5652

Hex is a variable defined in that function. Writing Hex.DC will refer to 4 bytes within that structure, on the stack of this function call.

pHex points somewhere determined by the caller. Hex = *pHex; will copy the contents of the arriving structure to your local structure. They are different blocks of memory.

Draw a picture of the stack, block out the activation frame of a call, fill in Hex there. Draw other blocks where memory is allocated (global, dynamic, earlier calls) and draw arrows to them to indicate pointers.

Upvotes: 2

Related Questions