Array is a collection of similar datatypes stored in contiguous memory location.
case 1: Normally array name represents the Base Address of the array. According to this a
and gives the base address. You Know &a
gives The base address
case 2: A pointer to the first element in the array, Gives you the Base address of the array.
int a[5] = {1,2,3,4,5};
int *ptr;
ptr=a; // Here p holds the address of the first element in the array
ptr=ptr+1; // address incremented to next element. now it will point to 2
printf("%d\n",*ptr); // it prints 2.
case 3: From your code
Normally a
and &a
are starting address. a+1
means in will point to the second element in the array. But &a+1
means it will point to the next array. it will increment the whole array size(that means in your case 20 bytes).
int a[5] = {1,2,3,4,5}; // consider base address is 1000. so &a+1 is 1020. that is next array(but here you did not have).
int *ptr=(int *)(&a+1); // you are assigning 1020 address to ptr. for checking print the address of ptr
printf("%d,%d", *(a+1),*(ptr-1)); // as i told a+1 will point to 2nd element. so it prints 2.
//ptr is pointing to 1020, you are decreasing one element so it point to 1016. the value at 1016 is 5.
//(how? 1 is 1000 means, 2 is 1004, 3 is 1008..... 5 is 1016(because integer needs 4 bytes of address for each elements)).
Remember in array elements are stored in Contiguous memory locations.
int b = 1; // consider address of b is 1000
int *cx = &b; // assingning to *cx
int *dx = (int *)(&cx + 1); // &cx is pointer address(it is not 1000, so consider &cx is 2000)
// &cx+1 means it points to 2004, and you are assigning to *dx
printf("%d %d", *(cx), *(dx -1)); // here *(cx) will print 1. but *(dx-1) means it point to 2000. we dont know what value is there.
// so it will print some garbage value.