C++ 为什么指向数组的两个指针是可以比较

1、问题的引入
当读到有字符数组进行反转的代码时,可以看到有指向同一个数组的两个指针的大小比较,但是平时用到的指针一般都是和nullptr进行比较,所以就有了这个标题的疑问;代码如下:

#include <iostream>
#include <stdio.h>
int main()
{
    int name[8]={1,2,3,4,5,6,7,8};
    int *p1=name;
	int *p2 =p1+8-1;
	while(p1 < p2)
	{
		int temp = *p1;
		*p1 = *p2;
		*p2 = temp;
		p1++;
		p2--;
		printf("p1 = %02x\n", p1);
		printf("p2 = %02x\n", p2);
	}
	for(int i = 0; i < 8; i++)
	{
		std::cout << name[i] << std::endl; 
	}
	return 1;
}

看到有指向同一个数组的两个指针,p1指向数组的开始位置,p2指向数组的末尾位置,结束条件就是判断p1<p2,就是指针的比较;
2、问题的思考的思路
(1)首先想到的是从进程的虚拟空间来解释,数组是栈上的空间,但是栈的空间是由大到小进行分配的,所以理论上即使是内存连续的数组,数组首元素的位置地址应该是高于数组尾元素的地址,但是数组的空间并不是分开申请的,而是一次性申请的整个数组大小的空间,所以数组的地址是由低地址到高地址的,所以指向同一个数组的两个指针是可以进行大小的比较,堆上的内存同样的道理;
(2)C99的标准里有规定是指向同一个数组的两个指针的比较的说明,这个是同事告诉我的,看一下规定;
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object or incomplete types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal.If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
总体就是说可以比较的;


版权声明:本文为hhaijiuwo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。