How is the output 15 here? can someone explain it to me? I didn't really understand the use of putc and stdout

59 Views Asked by At
     int *z;
 char *c = "123456789";
 z = c;
 
 putc(*(z++),stdout);
 putc(*z, stdout);
 
 return 0;

The output is 15 thats for certain but how does this happen.

1

There are 1 best solutions below

0
Tenobaal On

Let's look at this code operation by operation. For this reason I have rewritten it (both codes are equivalent):

int *z;
char *c = "123456789";
z = c;

putc(*z, stdout);
z++;
putc(*z, stdout);

Because you use z++, the post increment, ++z would be pre-increment, the value of z is fetched, before incrementing it.

After the first three lines everything looks as expected. Both pointers point to the string "123456789". But the first putc is already interesting. z is a pointer to an integer, but it points to a character, so fetching the pointer value fetches 4 bytes instead of one. Because you are using a little endian machine, the the 3 higher bytes are truncated by converting the integer (with the bytes "1234" = 875770417) to a character. The lowest byte ('1' = 49) remains.

In the line z++;, not 1, but 4 is added to the address z points to, because z is expected to point to an integer with the size of 4 bytes. On your system an int has apparently 4 bytes. So instead of pointing to "23456789" it points to "56789". This is just how pointer arithmetic work in C.

The last line works exactly like the 5th, but this time z points to "5678" (= 943142453) which gets truncated to 53 (= '5'). On big endian machines, the code would print "48" instead.