有没有办法找出指针在数组中的位置?
假设我们已经这样做了:
int nNums[10] = {'11','51','23', ... }; // Some random sequence
int* pInt = &nNums[4]; // Some index in the sequence.
...
pInt++; // Assuming we have lost track of the index by this stage.
...
有没有一种方法可以确定数组 pInt
中的哪个元素索引“指向”而无需再次遍历数组?
最佳答案
是的:
ptrdiff_t index = pInt - nNums;
当指向数组元素的指针被减去时,它与减去下标相同。
类型ptrdiff_t
在 <stddef.h>
中定义(在 C++ 中它应该是 std::ptrdiff_t
并且应该使用 <cstddef>
)。
关于c++ - 数组指针算术题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2554934/