Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Memory Allocation

I am trying to learn the concept of pointers in depth. In the below code , I create an array an create a pointer to each of the element.

int bucky[5];
int *bp0 = &bucky[0];
int *bp1 = &bucky[1];
int *bp2 = &bucky[2];

cout<<"bp0 is at memory address:"<<bp0<<endl;
cout<<"bp1 is at memory address:"<<bp1<<endl;
cout<<"bp2 is at memory address:"<<bp2<<endl;

These are the memory allocations given to the array elements.

bp0 is at memory address:0x0018ff3c
bp1 is at memory address:0x0018ff40
bp2 is at memory address:0x0018ff44

With my limited knowledge in c++ , I am aware that memory is allocated contiguously to an array. But looking at the output closely, bp0 looks out of place.

According to me bp0 should be at 0x0018ff36. Or is it that the locations 0x0018ff3c , 0x0018ff40 , 0x0018ff44 are continuous in the CPU?

So is it possible that two contiguous memory allocations are not assigned in a progression?

like image 450
m0bi5 Avatar asked Sep 13 '26 00:09

m0bi5


1 Answers

           +---+---+---+---+---+---+---+---+---+---+---+---+
           |      bp0      |      bp1      |      bp2      |
           +---+---+---+---+---+---+---+---+---+---+---+---+
  0x0018ff3c   d   e   f  40   1   2   3   4   5   6   7   8

Assuming size of int is 4 bytes and as bp0 points at 0x0018ff3c.

bp1 = bp0 + 4 = 0x0018ff40
bp2 = bp1 + 4 = 0x0018ff44

like image 113
Mohit Jain Avatar answered Sep 15 '26 15:09

Mohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!