pointer and address to that pointer lead to the same thing

后端 未结 2 1880
自闭症患者
自闭症患者 2021-01-29 08:18

When I saw this those lines :

BYTE MessageToProcess[MAX_MESSAGE_LENGTH];
TcpIpPacketHdr *pHdr = (TcpIpPacketHdr*)&MessageToProcess;

I said

2条回答
  •  执念已碎
    2021-01-29 08:31

    The variable MessageToProcess is an array. It's placed somewhere in memory. By using &MessageToProcess we get the address of that place in memory where the array is stored. The type of &MessageToProcess is BYTE (*)[MAX_MESSAGE_LENGTH].

    When you use MessageToProcess without the address-of operator, it decays to a pointer to the first element, i.e. &MessageToProcess[0]. The type of that is BYTE *.

    For something simple as the examples shown in the question, those two addresses are the same. The difference comes when you try to do something more with these pointers. For example if you do (&MessageToProcess)[1] you will not get the same thing as when doing MessageToProcess[1].


    To visualize it somewhat, lets say we have the following definition:

    int a[4] = { 0, 1, 2, 3 };
    

    Then it's something like this:

    &a              &a+1
    |               |
    v               v
    +---+---+---+---+
    | 0 | 1 | 2 | 3 |
    +---+---+---+---+
    ^   ^
    |   |
    a   a+1
    

提交回复
热议问题