I've switched to C recently and was trying to figure out pointers.
#include <stdio.h>
int main()
{
int arr[5] = {1,2,3,4,5};
int *a = &arr;
printf("Array : %p\n", arr);
for(int i=0; i<5; i++)
{
printf("Value and Address of Element - %d : %d\t%p,\n", i+1, arr[i], &arr[i]);
}
printf("Pointer to the Array : %p\n", a);
printf("Value pointed by the pointer : %d\n", *a);
a = (&a+1);
printf("Pointer after incrementing : %p\n", a);
return 0;
}
However, the following line doesn't seem to work.
a = (&a+1);
After printing the incremented value of the pointer a, it still points to the array (arr). Here's the output of the program:
Array : 0x7ffe74e5d390
Value and Address of Element - 1 : 1 0x7ffe74e5d390,
Value and Address of Element - 2 : 2 0x7ffe74e5d394,
Value and Address of Element - 3 : 3 0x7ffe74e5d398,
Value and Address of Element - 4 : 4 0x7ffe74e5d39c,
Value and Address of Element - 5 : 5 0x7ffe74e5d3a0,
Pointer to the Array : 0x7ffe74e5d390
Value pointed by the pointer : 1
Pointer after incrementing : 0x7ffe74e5d390
As you can see the pointer 'a' still points to the first element. However, in theory shouldn't 'a' point to whatever's after the last element (Given that &a + 1 increments the pointer by the size of the entire array - source: difference between a+1 and &a+1)
Could someone explain why?
int *a = &arr;should not compile.