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

Recommended Answers

All 3 Replies

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.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.