C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C++指针比较大小(详解版)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
可以使用 @L_618_0@ 的任何关系运算符来比较指针包括 >、<、==、!=、>=、<=。

如果内存中的一个地址在另一个地址之前,则第一个地址被认为是 "小于" 第二个地址。在一个数组中,所有元素都存储在连续的内存位置,所以元素 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 不是空指针之后才打印该指针指向的整数。

大佬总结

以上是大佬教程为你收集整理的C++指针比较大小(详解版)全部内容,希望文章能够帮你解决C++指针比较大小(详解版)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: