Printing Addresses and Accessing Elements of an Array

Explore different methods of printing addresses and accessing elements of an array.

Printing the address of array elements

There are two ways to print the address of array elements:

  • Using the ampersand operator
  • Using simple arithmetic

Using the ampersand operator

We can print the addresses of array elements using the expressions: &a[ 0 ], &a[ 1 ], &a[ 2 ], etc.

C
#include<stdio.h>
int main() {
int a[] = {7, 9, 16, -2, 8};
// Use ampersand operator for printing address of an array elements
printf("%u %u %u\n", &a[0], &a[1], &a[2]);
}

Using simple arithmetic

Since the array variable name is a pointer, pointing to the 1st1^{st} element of an array, mentioning the name of an array always fetches its base address, starting address, or the address of its 0th0^{th} element. Therefore, the addresses of array elements can also be printed using the expressions: a, a + 1, a + 2, etc.

Incrementing the pointer results in the pointer pointing to the next immediate location of its type. Hence, a will give us the address of the 1st1^{st} element, and a+1 will give us the address of the 2nd2^{nd} element.

C
#include<stdio.h>
int main() {
int a[] = {7, 9, 16, -2, 8};
printf("%u %u %u\n", &a[0], &a[1], &a[2]);
// Use simple arithmetics to print adddress of an array
printf("%u %u %u\n", a, a+1, a+2);
}

Accessing elements of an array

We can access array elements using the expressions: subscript notation, a[ i ], or pointer notation, *( a + i ).

C
#include<stdio.h>
int main() {
int a[] = {7, 9, 16, -2, 8};
int i;
printf("%d %d %d\n", *a, *(a+1), *(a+2));
for (i = 0; i <= 4; i++){
// Accessing array elements using pointer notation
printf("%d ", *(a+i));
}
printf("\n");
for (i = 0; i <= 4; i++){
// Accessing array elements using subscript notation
printf("%d ", a[i]);
}
}

Note: Since every a[ i ] gets expanded to *( a + i ), the expression, a[ i ], is the same as i[ a ].