Chen Avnery
Chen Avnery

Reputation: 122

Printf %X identifier - Weird behaviour with pointers

I was recently in an interview and was given the question:


Look at this code and write its output:

unsigned char buff[] = { 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, 0x33, 0x33, 0x33, 0x33 };
unsigned long *pD = (unsigned long *)buff;
unsigned short *pS = (unsigned short *)buff;
void *pEnd = &buff[sizeof(buff) - 1];

for (; pD < pEnd; pD++)
    printf("0x%X\n", *pD);

for (; pS < pEnd; pS++)
    printf("0x%X\n", *pS);

return 0;

Now assuming the system is 32bits and unsigned long is 4 bytes, the answer is:

Now for my question:

Why does it print only 16 bits with the unsigned short variable? I know that unsigned short is 2 bytes but printf knows how much bytes to parse from the stack based on the %X, which is read as unsigned int. I would assume that it will read 4 bytes (unsigned int) at all times, with sometimes junk (or corrupted stack eventually).

What do you think?

Thanks!

Upvotes: 1

Views: 527

Answers (2)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

*pS is of type unsigned short, so this value is used. Though printf expects an int for %X, you provide an unsigned short, which is promoted to int. So the order is: first 2 bytes are read from your array because *pS is unsigned short. Then this unsigned short value is promoted to int.

Upvotes: 1

dornhege
dornhege

Reputation: 1500

You don't have pointers in the output. By dereferencing you're telling printf to output a short and that's what it does. %X only displays that as hex.

Upvotes: 0

Related Questions