Sequential memory allocation

I used the following code to find the difference between the address of two consecutive memory blocks in an array. Although the printed size of each element ('int' here) is 4, the difference between the address of two consecutive blocks containing that element turns out to be 1. The difference shouldn't 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

+3


source to share


3 answers


This is because pointer arithmetic . The type &(a[i])

is int*

, which points to the block of memory that can be stored int

. If you hit that pointer on one, it will point to the next block of memory that the other can store int

. This is why the difference between the two int*

is equal 1

.

You can print out what you are trying to achieve by specifying the type of the pointer int*

to the type of the pointer char*

and then compute the difference:



cout << (reinterpret_cast<char*>(&a[i]) - reinterpret_cast<char*>(&a[i - 1]));

      

+1


source


The "difference measure" is the number int

s, not the char

difference between two type pointers T*

is the number of type objects T

between them.

Please 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 in p

gives p + 1

which is exactly what you expect.

+1


source


You can get the expected value by casting to integers, for example unsigned long long

:

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

      

Casting for unsigned int

enough for a 32-bit system.

If not selected, then it performs pointer arithmetic, resulting in 1.

+1


source







All Articles