linux int指针 大小,C++指针比较大小(详解版)

可以使用 C++ 的任何关系运算符来比较指针,包括 >、=、<=。

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

b3077561aa46dd4f12def965677e6e11.gif

图 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

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 不是空指针之后才打印该指针指向的整数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值