编程知识 cdmana.com

Why are two pointers to arrays comparable in C++

1、问题的引入
When reading code that has a character array to reverse,You can see that there is a size comparison of two pointers to the same array,But the pointers that are usually used are generally andnullptr进行比较,Hence the question of the title;代码如下:

#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;
}

See that there are two pointers to the same array,p1指向数组的开始位置,p2Points to the end of the array,The end condition is the judgmentp1<p2,It's a pointer comparison;
2、problem thinking ideas
(1)The first thing that comes to mind is to interpret from the virtual space of the process,Arrays are space on the stack,But stack space is allocated from large to small,So in theory even memory contiguous arrays,The address of the first element of the array should be higher than the address of the last element of the array,But the space of the array is not allocated separately,Instead, the entire array-sized space is allocated at one time,So the address of the array is from low address to high address,So two pointers to the same array can be compared in size,The same goes for memory on the heap;
(2)C99The standard specifies that it is a description of the comparison of two pointers to the same array,This is what a colleague told me,look at the regulations;
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.
Overall it is comparable;

版权声明
本文为[hhaijiuwo]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/266/202209230827317181.html

Scroll to Top