2

I have a puzzling question (at least for me)

Say I declare an integer array:

int arr[3];

Conceptually, what happens in the memory is that, at compile time, 12 bytes are allocated to store 3 consecutive integers, right? (Here's an illustration)

Based on the illustration, the sample addresses of

arr[0] is 1000,

arr[1] is 1004, and

arr[2] is 1008.


My question is:

If I output the difference between the addresses of arr[0] and arr[1]:

std::cout << &arr[1] - &arr[0] << std::endl;

instead of getting 4,

I surprisingly get 1.

Can anybody explain why it resulted to that output?

PS: On my computer, an int is 4 bytes.

Christian
  • 25
  • 4

1 Answers1

0

Pointer arithmetic automatically divides the value by the size of the base type so this is not surprising at all since one would expect to get 4 / 4 which is 1. Cast to unsignd char * to see the difference.

#include <iostream>

int
main(void)
{
    int arr[2];

    std::cout << &arr[1] - &arr[0] << std::endl;
    std::cout << reinterpret_cast<unsigned char *>(&arr[1]) -
        reinterpret_cast<unsigned char *>(&arr[0]) << std::endl;

    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97