views:

118

answers:

1
#include<iostream>
#include<conio.h>

using namespace std;
int main()
{
           int x = 65;
           int *ptr = &x;
           char * a= (char *)ptr;
           cout<<(int)*(a);
           getch();return 0;
}           

Sixeof(ptr) and Sizeof(a) display 4
Sizeof(int) displays 4 and sizeof(char) displays 1
So 65 is stored in 4 bytes ie
00000000 00000000 00000000 01000001 and address of first bytes is stored in ptr

In the above code I have type casted the int* to char* in a motive to print the value stored in x(type int) first byte.

So after typecasting "a" stores the first byte address ie contained in ptr as well Now on displaying (int)*a shouldn it consider only first byte for showing the value..?? but the output is 65 instead of 0(first byte value)..Where am I going wrong..?

what I have learnt is

char * ptr1;
ptr1++;  //Ptr1 goes to the next byte..*ptr1 will display only 1 byte value

int  * ptr2;
ptr1++;  //Ptr2 goes to the next 4 byte..*ptr2 will display value conmtain in 4 bytes

PS - I am working on Dev-C++

+13  A: 

Your machine is little-endian, and least significant bytes go first.

rkhayrov
... and before the questioner makes the reverse mistake: little-endian only affects what happens when you store a value in memory and then access its bytes individually. It doesn't affect the meaning of the `>>` and `<<` shift operators: less significant bits are always to the "right" regardless of endian-ness.
Steve Jessop
The address stored in "ptr" and "a" are same , so does that means the LSB address is stored in them..?
Thanks for the answer..!