Difference between array name +1 and array name address +1 in C ++

The array name in C / C ++ will degenerate into a pointer, so the array name a actually refers to the address of the first element of the array. The array name is special as a pointer. It is in the memory area it points to. The value of & a is the same as the value of a (you can observe the output), but the type and meaning are different. The addition operation of the pointer is closely related to the data type pointed to.
For example:
int a [10]; a is equivalent to int *, if you add 1 (a + 1) to it, it is equivalent to a + 1 * sizeof (int). However, the type of & a is equivalent to int **, which is the so-called pointer to the array, and is a secondary pointer of the array element type. Adding 1 to it is equivalent to & a + 1 * sizeof (a), so it will be offset by an array length.

First, a very simple code:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
	int x=5,*p_int=&x;
	int aa[10]={1,2,3,4,5,6,7,8,9,10};
	
	cout<<"\naa:\t"<<aa<<"\naa+1:\t"<<aa+1;
	cout<<"\n&aa:\t"<<&aa<<"\n&aa+1:\t"<<&aa+1<<"\n\n";
	
	cout<<"\np_int:\t"<<p_int<<"\np_int+1:"<<p_int+1;
	cout<<"\n&p_int:\t"<<&p_int<<"\n&p_int+1:"<<&p_int+1;
	
	return 0;
}

The running result is:

aa:          0x6ffe00
aa+1:     0x6ffe04
&aa:       0x6ffe00
&aa+1:  0x6ffe28

p_int:        0x6ffe3c
p_int+1:      0x6ffe40
&p_int:     0x6ffe30
&p_int+1: 0x6ffe38


It is concluded that:
① The array name is +1, which is the number of bytes in the size of the array element; the address of the array name is +1, which is the number of bytes in the entire array size
② The pointer +1 is the number of bytes corresponding to the pointer type; pointer 'S address +1 is +8
 

Published 42 original articles · Like 10 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/qq_37659294/article/details/102331098