When I point a pointer to an array. Why does the pointer and the index[0] of the array I am pointing to have different memory addresses?

Viewed 32
#include <stdio.h>

int main()
{
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

int *p = &arr;

printf("Memory address of first index: %p\n", &arr[0]);
printf("Memory address of pointer: %p\n", &p);

return 0;
}

OUTPUT Memory address of first index: 000000000061FE00 Memory address of pointer: 000000000061FDF8

They are are not the same. Is my machine bad?

2 Answers

arr is an array. It and its elements start at some place in memory.

p is a pointer to the array. Its value is an address. That address needs to be stored somewhere else in memory. That place is different from where the array is stored.

printf("%p\n", (void *) p); prints the value of p, which will be the address of arr (and of &arr[0], since the first element is at the start of the array).

printf("%p\n", (void *) &p) prints the address of p, which is where p is.

First of all the compiler should issue a message relative to this declaration

int *p = &arr;

The problem is that the right hand side expression has the type int( * )[5] while the initialized object has the type int * and there is no implicit conversion between these two pointer types.

You should write either

int *p = arr;

In this case the array designator is implicitly converted to a pointer to its first element. Or

int ( *p )[5] = &arr;

The pointer p occupies its own extent of memory. So its address is different from the address of the extent of the memory occupied by the array arr.

On the other hand, if you will output the value stored in the pointer p like for example

printf("Memory address stored in the pointer p: %p\n", ( void * )p);

then it will be equal to the address of the first element of the array arr

printf("Memory address of first index: %p\n", ( void )&arr[0]);
Related