
如果内存中的一个地址在另一个地址之前,则第一个地址被认为是 "小于" 第二个地址。在一个数组中,所有元素都存储在连续的内存位置,所以元素 1 的地址大于元素 0 的地址,如图 1 所示。
图 1 内存地址的大小关系
因为数组中的每个后续元素的地址都会变大,所以下面的布尔表达式都是真的:
&array[1] > &array[0]
array < &array[4]
array == &array[0]
&array[2] != &array[3]
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
if (ptrToInt != nullptr) cout << *ptrToInt;else cout << "null pointer";只有在检查发现 ptrToInt 不是空指针之后才打印该指针指向的整数。
总结
以上是内存溢出为你收集整理的C++指针比较大小(详解版)全部内容,希望文章能够帮你解决C++指针比较大小(详解版)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)