Difference between address using array_name V.s &array_name?

Viewed 58

so I was studying about arrays and pointer to an array and I found this code. I was wondering why the last one's address is FE14, isn't it suppose to be the address of the first element plus the (size of data type ) which is 4, so I should be FE04 ?

#include <stdio.h>
int main()
{
    int arr[5];
    printf("%p\n",arr); //----> the output FE00
    printf("%p\n",arr+1); //----> the output FE04
    printf("%p\n",&arr); //----> the output FE00
    printf("%p\n",&arr+1); //----> the output FE14
}
2 Answers

This is confusing because of the way C arrays can decay into pointer expressions.

With arr and arr+1, the data type of the pointer is int, which on your system is 4 bytes, hence why you see the 4 byte difference between FE00 and FE04.

With &arr and &arr+1, the data type of the pointer is int[5], which is 20 bytes, hence why you see the 20 byte difference between FE00 and FE14

It's a difference of 0x14, which is:

  1 * 16^1 + 4 * 16^0
= 1 * 16   + 4 * 1
= 16       + 4
= 20

If you change the size of your int arr[5] from being 5 ints long to say, 500, you'll see a bigger difference between &arr and &arr+1.

printf("%p\n", arr+1);

In this code, arr is an integer pointer, so arr + 1 results in arr + 1 * sizeof(int), which is 4.

printf("%p\n",&arr+1);

In this one, &arr is a pointer to an array of 5 int, so &arr + 1 results in &arr + 1 * sizeof(int[5]), which is 20 (14 in hexadecimal)

Related