Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does pointer adressing work in c++

I am confused about pointer pointing to address of variable image

it points to last two bytes how does this work

#include <iostream>
using namespace std;

int main()
{
    int i = 1;
    short *j  = (short*)&i;
    cout << *j << endl;
}

.

like image 900
SRN Avatar asked Nov 28 '22 09:11

SRN


1 Answers

A pointer normally holds the address of the beginning of the referred-to item.

From the sound of things, you're apparently using a little-endian system [edit: which is no surprise -- just for example, current (Intel) Macs and all Windows machines are little-endian], which means the least significant byte of your 4-byte int comes first in memory instead of last:

0000001 00000000 00000000 00000000

When you use a pointer to short to look at the first two bytes, you get:

0000001 00000000

which is exactly how it expects to see a value of 1 represented as a two-byte number, so that's what you get.

As implied by the name "little-endian" there are also big-endian systems, where the data would be laid-out as you've illustrated above. On such a machine, you'd probably get the results you expected. Just to be complete, there are also a few systems that use rather strange arrangements that might run something like byte1 byte0 byte3 byte2.

like image 132
Jerry Coffin Avatar answered Dec 05 '22 12:12

Jerry Coffin