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

后端 未结 12 1161
难免孤独
难免孤独 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:50

    You should think of pointers as being addresses of virtual memory: modern consumer operating systems and runtime environments place at least one layer of abstraction between physical memory and what you see as a pointer value.

    As for your final statement, you cannot make that assumption, even in a virtual memory address space. Pointer arithmetic is only valid within blocks of contiguous memory such as arrays. And whilst it is permissible (in both C and C++) to assign a pointer to one point past an array (or scalar), the behaviour on deferencing such a pointer is undefined. Hypothesising about adjacency in physical memory in the context of C and C++ is pointless.

提交回复
热议问题