int a=320;
char *p;
p=(char *)&a;
printf("%d",*p);
gives 64\\\not sureif p or *p in pf

wat in the world does
(char *)&a does ??
sum1 help plzzzz

3
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by N1GHTS

It's called type punning. By casting the address of an integer into a pointer to char, you can directly access the bytes that make up the integer (note that char is synonymous with a byte).

This is a less complicated way to do the same thing...

``````int a=320;
printf("%d",(char)a); // Only return the first byte of the integer using a cast``````

"Type Punning" as in your example is best used for random access of said bytes.

``````int a=320;
char *p;
p=(char *)&a;
printf("%d",p[1]); // Access the second byte of the integer``````

Here is an inline example:

``````int a=320;
printf("%d",((char *)&a)[1]); //  Print the second byte of the integer.``````

Edited by N1GHTS: n/a

Here is an example of a "pointer ocean" as your title suggests. It will print the integer by first cutting the integer into 4 individual bytes and then puts them back together for no good reason.

``````int a = 123456789;

// "Pointer Ocean" technique to print 'a'
printf("a=%d\n",*((unsigned char *)&a)+(*(((unsigned char *)&a)+sizeof(char))<<(sizeof(char)*8))+(*(((unsigned char *)&a)+(sizeof(char)*2))<<((sizeof(char)*8)*2))+(*(((unsigned char *)&a)+(sizeof(char)*3))<<((sizeof(char)*8)*3)));

// Equivalent code
printf("a=%d\n",a);``````

Here is the Output:

``````a=123456789
a=123456789``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.