Variable name is a pointer to the first element
A variable name is an alias to the address of where the data is stored in the memory; hence, it’s a pointer.
You can declare a variable and print the address of it using %p
format in C language.
int val;
printf("address: %p\n", &val); // address: 0x7ff7b5611bd8
Same principle applies to the array. The name of the array itself will point to the first element in the array. We can prove that arr[0]
is equivalent to dereferencing a pointer at 0-th index, *arr
or *(arr+0)
.
int arr[] = {1, 2, 3, 4, 5};
// 0x7ff7b3c3fbe0 == 0x7ff7b3c3fbe0 == 0x7ff7b3c3fbe0
printf("%p == %p == %p\n", &(arr[0]), (arr+0), arr);
// 1 == 1 == 1
printf("%d == %d == %d\n", arr[0], *(arr+0), *arr);
This is how index operator ([]
) is calculating the offset. When we do arr + 2
, we’re not simply adding a value 2 to the array. We are offsetting by 2 positions from arr
, which is the 1st element, giving us the location of a 3rd element.
int arr[] = {1, 2, 3, 4, 5};
printf("arr[0] = %d\n", *arr); // 1
printf("arr[1] = %d\n", *(arr+1)); // 2
printf("arr[2] = %d\n", *(arr+2)); // 3