认为C ++指针作为内存地址在什么程度上是可以接受的? [英] To what extent is it acceptable to think of C++ pointers as memory addresses?
问题描述
当你学习C ++,或至少当我通过 C ++ Primer 学习它时,指针被称为他们指向的元素的内存地址。我想知道在什么程度上这是真的。
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 what extent this is true.
例如,执行两个元素 * p1
和 * p2
具有属性 p2 = p1 + 1
或 p1 = p2 + 1
/ strong>它们在物理内存中相邻?
For example, do two elements *p1
and *p2
have the property p2 = p1 + 1
or p1 = p2 + 1
if and only if they are adjacent in physical memory?
推荐答案
应该将指针看作是 memory:现代操作系统在物理内存和你所看到的指针值之间至少要有一层抽象。
You should think of pointers as being addresses of virtual memory: modern operating systems place at least one layer of abstraction between physical memory and what you see as a pointer value.
至于你最后的陈述,你不能那个假设,即使在虚拟内存地址空间。指针算术仅在连续存储器(例如数组)块内有效。虽然允许(在C和C ++中)将指针分配给超过数组(或标量)的一个点,但是引用这样的指针的行为是未定义的。在C和C ++的上下文中假设物理内存中的邻接是无意义的。
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.
这篇关于认为C ++指针作为内存地址在什么程度上是可以接受的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!