File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pointers

 
aaka jain
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
main(){
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??
thanks
 
Ramesh Pramuditha Rathnayake
Ranch Hand
Posts: 178
2
Java MySQL Database Netbeans IDE
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Value of i is stored in memory as follows.. As i is an int, it has 4byte memory allocation.(byte is separated by comma).

00000000,00000000,00000001,00000001

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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic