Stephen Jacob
Stephen Jacob

Reputation: 901

Address not contiguous in multiple pointers

I am trying to refresh my knowledge on pointers. I don't seem to understand why cout shows me the value of the object rather than address at the line showing ((*alpha+i)+j). The same output is shown when using &((*alpha+i)+j). The reason I ask is because I thought memory allocation is contiguous but based on the output of the address, its,

Address 0: 0x19d7010  
Address 1: 0x19d7018 
Address 2: 0x19d7020
Address 3: 0x19d7028
Address 4: 0x19d7030

I thought it would be 10, 15, 20, 25 & 30

#include <iostream>

using namespace std;

int main( int argc, char **argv) {

char ** alpha;
alpha = new char * [5];
cout<<"Address alpha: "<<alpha<<'\n';


cout<<"Size of alpha: "<<sizeof(alpha)<<'\n';
for (int i=0; i<5; i++)
{
*(alpha+i)=new char [5];
cout<<"Address "<<i<<": "<<(alpha+i)<<'\n';

if(i<2)
for(int j=0; j<5; j++)
*(*(alpha+i)+j)='t';
else
for(int j=0; j<5; j++)
*(*(alpha+i)+j)='o';

for(int j=0; j<5; j++)
cout<<"Value "<<i<<": "<<(*(alpha+i)+j)<<'\n';

}

for(int i=0; i<5; i++){
cout<<"Value of i: "<<i<<'\n';
delete[] *(alpha+i);
}
delete[] alpha;
}

Upvotes: 1

Views: 57

Answers (1)

Sanoob
Sanoob

Reputation: 2474

You are using 64 system In that size of pointers will be 8 bytes. If you take 8 bytes your address locations, You results are in continues locations

19d7018 − 19d7010 = 8
19d7020 − 19d7018 = 8
19d7028 − 19d7020 = 8

And How your said it should be 19d7020,19d7015,19d7010 etc.. ? if you take like that then pointer size will 5 bytes. I think none of the architecture take 5 bytes for pointers.

19d7015 − 19d7010 = 5

Upvotes: 1

Related Questions