File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 178

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.

I agree. Here's the link:
subject: pointers
It's not a secret anymore!