首先,binky视频可能会有所帮助.这是一段关于指针的精彩视频.关于算术,这里有一个例子:
int * pa = NULL;
int * pb = NULL;
pa += 1; // pa++. behind the scenes, add sizeof(int) bytes
assert((pa - pb) == 1);
print_out(pa); // possibly outputs 0x4
print_out(pb); // possibly outputs 0x0 (if NULL is actually bit-wise 0x0)
(请注意,严格递增包含空指针值的指针是未定义的行为.我们使用NULL,因为我们只对指针的值感兴趣.通常,仅在指向数组元素时使用递增/递减).
下面显示了两个重要的概念
以一个实际例子为例.假设您编写了一个函数,人们为您提供了一个开始和结束指针(在C++中非常常见):
void mutate_them(int *begin, int *end) {
// get the amount of elements
ptrdiff_t n = end - begin;
// allocate space for n elements to do something...
// then iterate. increment begin until it hits end
while(begin != end) {
// do something
begin++;
}
}
ptrdiff_t
是(结束-开始)的类型.对于某些编译器,它可能是"int"的同义词,但对于另一个编译器,它可能是另一种类型.我们不知道,所以我们 Select 通用的typedef ptrdiff_t
.