如果内存中的一个地址在另一个地址之前,则第一个地址被认为是 "小于" 第二个地址。在一个数组中,所有元素都存储在连续的内存位置,所以元素 1 的地址大于元素 0 的地址,如图 1 所示。

图 1 内存地址的大小关系
因为数组中的每个后续元素的地址都会变大,所以下面的布尔表达式都是真的:
&array[1] > &array[0]
array < &array[4]
array == &array[0]
&array[2] != &array[3]
注意,比较两个指针与比较两个指针指向的值是不同的。例如,下面的 if 语句比较存储在指针变量 ptr1 和 ptr2 中的地址:
if (ptr1 < ptr2)
但是,下面的语句则比较了 ptr1 和 ptr2 指向的值:
if (*ptr1 < *ptr2)
比较地址的能力为程序员提供了另一种方式来确保指针不超出数组边界。下面的程序使用了数组 set 的起始地址对指针 numPtr 进行了初始化,然后指针 numPtr 开始遍历数组 set,直到它包含的地址等于数组的最后一个元素的地址。遇到边界之后,指针又向后遍历数组,直到它指向第一个元素。
// This program uses a pointer to display the contents of an integer array. It illustrates the comparison of pointers. #include <iostream> using namespace std; int main() { const int SIZE = 8; int set[ ] = {5, 10, 15, 20, 25, 30, 35, 40}; int *numPtr = set; // Make numPtr point to set cout << "The numbers in set are: /n"; cout << *numPtr << " "; // Display first element while (numPtr < &set[SIZE-1]) { // Advance numPtr to the next element numPtr++; // Display the value pointed to by numPtr cout << *numPtr << " "; } //Display the numbers in reverse order cout << "/nThe numbers in set backwards are:/n"; cout << *numPtr << " "; // Display last element while (numPtr > set) { // Move backward to the previous element numPtr--; // Display the value pointed to by numPtr cout << *numPtr <<" "; } return 0; }
程序输出结果:
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5
涉及指针的大多数比较都是使用指针和 0、NULL 或 nullptr 值进行比较,以确定指针是否指向合法地址。例如,假设 ptrToInt 被定义为一个指向 int 的指针,则以下代码将首先检查它是否为空指针。
if (ptrToInt != nullptr) cout << *ptrToInt; else cout << "null pointer";
只有在检查发现 ptrToInt 不是空指针之后才打印该指针指向的整数。
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/22130.html