This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes C / C++ and the fly likes pointers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "pointers" Watch "pointers" New topic


aaka jain

Joined: May 16, 2013
Posts: 12
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char *)iptr+1));

here in this program i m getting the output - 11
can somebody please explain me the output,and please also tell me that can we cast int pointer to character pointer in c??
Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 169

Value of i is stored in memory as follows.. As i is an int, it has 4byte memory allocation.(byte is separated by comma).


The address of the byte 00000001 (last one) is stored in iptr. As iptr is an int pointer, if we increase the value of iptr by one, address changes in 4 bytes.

Data type char has only 1 byte memory location. Therefore, if we increase the character pointer value by one, address changes in 1 byte.

(char*)iptr --> Address of 0000001 (last one)
*((char*)iptr) --> Value of 0000001 only as char stores only one byte. Therefore value is 1.
(char*)iptr + 1 --> char pointer is increased by one. Therefore this has the address of 0000001 (before the last one)
*((char*)iptr +1) --> Value of the stored value. As earlier it is 1.

Therefore your result should be 11.

It is sorta covered in the JavaRanch Style Guide.
subject: pointers