#include <stdio.h>
int fun(int a)
{
char *arr[] = {"0000", "0001","0010","0011","0100",
"0101","0110","0111","1000","1001","
1010","1011","1100","1101","1110","1111"};
unsigned char* p = (unsigned char*) &a ;
p+=3;
int i;
for(i = 0; i < sizeof a; i++) {
int d = (*p)>>4;
printf("%s", arr[d]);
d = (*p) & 0xf;
printf("%s ", arr[d]);
p--;
}
}
How many 1s will be printed by the below function when called with the argument 9? (Assume sizeof int as 4 bytes)
My thinking: a being an integer will stored in memory like this |00000000|00000000|00000000|00001001| suppose address are like this 100-101-102-103; Now p contains the address of a so it will contain 100 right? Now we typecasted it into char pointer now it will increment by 1 not by size of datatype. p+=3 after this statement p will contain 103 right? now for loop starts d=(*p) >> 4 Now isn't *p will contain 00001001 ? if we right shift 4 times d will contain 0 and arr[0] will be printed which is '0000' now d = (*p) & 0xf now if we do 00001001 bitwise and with 11111111 d should contain 9 right and a[9] should be printed but arr[0] is printing again.
Please help me to visualize it Thanks
Edit: output is 00000000 00000000 00000000 00001001
p+=3;should bep += sizeof a - 1;, compare that to theforstatement.aisn't stored as you think.p += (sizeof a) - 1;