p is a pointer to int.a is an array of int.So how does an array works(well pretty much)?You have a pointer(here the pointer of the array is a) and you say your system the offset you want and the pointer will go at the requested offset and give you access there.e.g. if i write a[3] then then the pointer a which located by default at the start of the array will move to the fourth cell(because we start counting from zero).
Also mind that a[3] is equivalent to *(a+3).
Code:
a
|
|
V
+-----+-----+-------+-----+-----+
|data |data|data2|data|data|
+-----+-----+-------+-----+-----+
so if i write *(a+2) the pointer will be transferred to data2
Code:
#include <stdio.h>
int main(void) {
int a[]={0, 1, 2, 3, 4};
printf("%d\n",a[3]);
printf("%d\n",*(a+3));
return 0;
}
So at your code line 11 sets pointer p to the fifth element of the array(because offset is +4 and we count from zero).So counter i is decreased in order to traverse the array in reverse.But because of the equivalent expressions i mentioned before p is now set back to the start of a.
Then in the second loop,we set pointer p again at the end of array a,because we move it four positions,starting from the zero.
Then p>=a means that the loop body is going to be executed as long as the pointer is at a cell which is in 'bigger' position(e.g. second element is at bigger position in comparisson with the first) or if the pointer p points where pointer a points.
Then it will make the pointer p point to a position with a smaller number(e.g from fifth cell to the fourth cell).
And when it says a[p-a] it means that p-a is resolved at an int .I run the program with this line
Code:
for (p=a+4; p>=a; p--) printf("%d %d %d %d\n",a[p-a],p,a,p-a);
output
Code:
4 4202512 4202496 4
3 4202508 4202496 3
2 4202504 4202496 2
1 4202500 4202496 1
0 4202496 4202496 0
the big numbers are addresses of course,because p and are pointers,so when writing *p we refer to where p points to ,but writing simple p we refer to it's own block of memory which contains it's address.
But if you do 4202512 - 4202496 you will find 16.Then p is decreased to point to a smaller position cell.So 4202508 - 4202496 =12 etc.
Notice that 4202496 remains as it was because a is not modified at all.
So why we find 16 but p-a gives as 4?
Why we find 12 but p-a gives as 3?
Well,in many systems int has size of 4.4 what?4 bytes .So every int is saved at a 4 bytes .An int is placed in an integer(you can imagine it as an array that holds the value of the number in binary).
So 4*4 requires 16 bits space to fit,3*4 12 bits to fit etc...
Edit->i am too slow,when starting writting no responses where here