To what extent is it acceptable to think of C++ pointers as memory addresses?

后端 未结 12 1125
难免孤独
难免孤独 2020-12-10 10:18

When you learn C++, or at least when I learned it through C++ Primer, pointers were termed the \"memory addresses\" of the elements they point to. I\'m wondering to

12条回答
  •  攒了一身酷
    2020-12-10 10:57

    Absolutely right to think of pointers as memory addresses. That's what they are in ALL compilers that I have worked with - for a number of different processor architectures, manufactured by a number of different compiler producers.

    However, the compiler does some interesting magic, to help you along with the fact that normal memory addresses [in all modern mainstream processors at least] are byte-addresses, and the object your pointer refers to may not be exactly one byte. So if we have T* ptr;, ptr++ will do ((char*)ptr) + sizeof(T); or ptr + n is ((char*)ptr) + n*sizeof(T). This also means that your p1 == p2 + 1 requires p1 and p2 to be of the same type T, since the +1 is actually +sizeof(T)*1.

    There is ONE exception to the above "pointers are memory addresses", and that is member function pointers. They are "special", and for now, please just ignore how they are actually implemented, sufficient to say that they are not "just memory addresses".

提交回复
热议问题