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.
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.
Let's look at this code operation by operation. For this reason I have rewritten it (both codes are equivalent):
Because you use
z++, the post increment,++zwould be pre-increment, the value ofzis fetched, before incrementing it.After the first three lines everything looks as expected. Both pointers point to the string "123456789". But the first
putcis already interesting.zis 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 addresszpoints to, becausezis expected to point to an integer with the size of 4 bytes. On your system aninthas 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
zpoints to "5678" (= 943142453) which gets truncated to 53 (= '5'). On big endian machines, the code would print "48" instead.