3

I used the following code to find the difference between the address of two consecutive blocks of memory in an array. Although the printed size of each item('int' here) is 4, the difference between the address of two consecutive blocks containing that item turns out to be 1. Shouldn't the difference be 4?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    int a[10];

    for(int i=0;i<10;i++)
        cin>>a[i];

    cout<<"size of 1 block = "<<sizeof(int)<<"\n";

    for(int i=1;i<10;i++){
    // cout<<"Difference between address of consecutive memory blocks\n";
       cout<<" "<<&(a[i])- &(a[i-1])<<"\n";
    }
    return 0;
}

Output

size of 1 block = 4
1
1
1
1
1
1
1
1
1

abhinav1602
  • 1,190
  • 17
  • 18

3 Answers3

1

It's because the pointer arithmetics. The type of &(a[i]) is int* which points to a memory block which can store an int. If you step this pointer by one, it will point to the next memory block which can store another int. This is the reason why the difference between two int* is 1.

You can print out what do you try to achieve by casting the int* pointer type to char* pointer type and then calculate the difference:

cout << (reinterpret_cast<char*>(&a[i]) - reinterpret_cast<char*>(&a[i - 1]));
Akira
  • 4,385
  • 3
  • 24
  • 46
1

The "difference measure" is number of ints, not chars – the difference between two pointers of type T* is the number of objects of type T between them.

Note that if

int* p = &a[k];

then

p + (&(a[i])- &(a[i-1])) == p + 1

that is, adding the difference between two consecutive elements to p gives p + 1, which is exactly what you would expect.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

You can get the value you expected by casting to integers, such as unsigned long long:

cout << " " << (unsigned long long)&a[i] - (unsigned long long)&a[i-1] << "\n";

Casting to unsigned int enough for 32-bit system.

If not casted, then it does pointer arithmetic, resulting in 1.

nglee
  • 1,913
  • 9
  • 32