• Home
  • 5.5 Array Element Addresses

5.5 Array Element Addresses

View Categories

5.5 Array Element Addresses

Each array element occupies a memory location and can be accessed through its address. The address-of operator & obtains the address of an individual element, while %p is used to print a pointer value.

#include <stdio.h>

int main(void)
{
    int numbers[] = {10, 20, 30};

    printf("Address of numbers[0]: %p\n", (void *)&numbers[0]);
    printf("Address of numbers[1]: %p\n", (void *)&numbers[1]);
    printf("Address of numbers[2]: %p\n", (void *)&numbers[2]);

    return 0;
}

Example Output #

The actual addresses vary between program executions and implementations.

Address of numbers[0]: 0x7ffe12345000
Address of numbers[1]: 0x7ffe12345004
Address of numbers[2]: 0x7ffe12345008

Explanation #

The expression:

&numbers[0]

obtains the address of the first array element.

Similarly:

&numbers[1]
&numbers[2]

obtain the addresses of the second and third elements.

Array elements are stored contiguously in memory. Therefore, the address of each successive element advances by the size of one element.

For an array of int, the address difference between adjacent elements is sizeof(int) bytes.

Address and Value Comparison #

Expression Meaning
numbers[0] Value of the first element
&numbers[0] Address of the first element
numbers[1] Value of the second element
&numbers[1] Address of the second element

The array name numbers also converts to a pointer to its first element in most expressions:

printf("%p\n", (void *)numbers);
printf("%p\n", (void *)&numbers[0]);

These two statements print the same pointer value. However, numbers is an array object, whereas &numbers[0] is a pointer to its first element. The distinction becomes important when working with pointers and sizeof.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *