This is a question from an interview to think of some questions, here to do a small summary!
First look at this interview question:
#include <stdio.h> Span class= "Hljs-keyword" >int Main () {int a[5
] = {1 , 2 , 3 , 4 , 5 }; int *pi = &a + 1 ; printf ( "%d , %d \ n" , * ( A + 1 ), * ( pi-1 )); return 0 ;}
The answer is 2, 5. As for why, I say my own understanding behind.
here is a place to note that the above code will have a warning in codeblock, but there is an error in VS2013 with the following error: The value of type int () [5] cannot be used to initializean entity of type ' int '. Of course, here we can do the coercion type conversion, then this error hint will disappear. The modified code is as follows:
#include <stdio.h>intMain () {inta[5] = {1,2,3,4,5};int *pi= (int *)(&a +1);printf("%d, %d\ n",*(A +1),*(Pi-1));return 0;}
This time, the compile run will get our correct answer 2, 5.
my personal understanding of the results of the analysis: the variable a points to the entire array of the first address, then the variable a each add 1 to move 4 bytes (equivalent to move from Point 1th to Point 2nd), and then take the variable A to address the operation, then &a each add 1 to move the 5 bytes (the equivalent of moving from the first address point to the current array to point to the next array's first address position). Probably as follows:
To extend the thought of this subject
#include <stdio.h>int main () {//ais a two-dimensional array inta[2][3];/*1、ais of type int (*) [2][3],aValue is a pointer to the array1An element address. **2, &aThe type of int*, &aValue is the first address that points to the entire array. **3、aThe number of bytes is4*6, &aThe number of bytes is4。 */printf ("a =%x, &a =%x\n",a, &a);printf"sizeof (a) =%d, sizeof (&a) =%d\n", sizeof (a), sizeof (&a));printf"A + 1 =%x, &a + 1 =%x\n",a+1, &a+1);/*1、a[0] is of type int (*) [3],a[0] value is a pointer to the array1Line element First1The address of an element. **2, &a[0] The type is int*, &a[0] value is a pointer to the array1The first address of an entire line element. **3、a[0] The number of bytes is4*3, &a[0] The number of bytes is4。 */printf ("a[0] =%x, &a[0] =%x\n",a[0], &a[0]);printf"sizeof (a[0]) =%d, sizeof (&a[0]) =%d\n", sizeof (a[0]), sizeof (&a[0]));printf"a[0]+1 =%x, &a[0] + 1 =%x\n",a[0] +1, &a[0] +1);}
The results of the operation are as follows:
From the result we can see that the a,&a,a[0],&a[0] address value is the same, but because the variable type is different, so the value of each move is the same.
Problems related to pointers in C language--on the relationship between the array name and the address of the group name