简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM