Code:
void Main () {int a[4] = {1,2,3,4};int *ptr0 = &a[0] + 1;int *PTR1 = (int *) (&a + 1); int *PTR2 = (int *) (int) A + 1); int *PTR3 = (int *) (A + 1);cout<<*ptr0<< "" <<ptr1[-1]<< "" <<*ptr2<< "" <<* ptr3<< "" <<endl;}
Explain:
&a[0]+1---->> pointer Plus: Depending on the type of pointer, the type of a[0] is int-that is integer
So: &a[0]+1 = &a[0]+4,ptr0 points to the second element of the array
&a+1---->> pointer plus one: depending on the type of pointer, &a is a pointer to the array
The size is 4*4=16 bytes, &a+1 = a+16, so ptr1 points to a space behind 4
Int (a) +1--->> general addition: first the address coercion type of a is converted to the integer number plus one
(int *) ((int) A + 1): Force the value of the newly-obtained integer to be converted to an address (int *)
The second byte that points to the element a[0], because the pointer is of type int, so the result is
A[0] The first byte of the second three bytes, and a[1]
a+1---->> array name plus one: array name (pointer constant) type: Because the array element is:
type int, so A is also an int pointer, a+1 = a+4, so point to the next element
Look at the following section of code:
#include <iostream>using namespace Std;int a[2] = {1,2};int main () {cout<< "a =" <<a << endl;cout<< "&a =" <<&a <<endl;cout<< "A + 1 =" <<a+1 <<endl; cout<< "&a + 1 =" <<&A+1<<ENDL;}
Explain:
General situation
<c and pointer >p141: The value of the array name is a pointer constant, which is the address of the first element of the array;
His type depends on the type of the array element: If the element type is char, the type of the array name is
Constant pointer to char type
Special cases
<c and pointer >p142: When the array name is the operand of the sizeof operator and the monocular operator &, the array name
Not represented as a pointer constant, sizeof (array name) = length of the array,& array name = is a pointer to an array
Pointer (not a pointer to a pointer constant)
&a-------------> A pointer to an array
A-------------> A pointer to a[0]
Forced type conversions (array name and array name fetch address)