+ 6
Gate question
12 is the output of the following code.How? #include <stdio.h> int main() { char s1[7]="1234",*p; p=s1+2; *p="0"; printf ("%s",s1); return 0; }
3 Answers
+ 5
I played around a bit. If you change it to
*p='0';
(single ' because it's a char), you get what you probably expect: 1204.
So it looks to me like "0" is interpreted as '\0', the string termination letter, which would mean that printf will now only read up to that point.
(Or it's undefined behaviour, that's something our C experts have to clarify. ;-))
+ 3
That "0" turns into '\0' is just pure coincidence.
"0" is nothing more than an address that exists somewhere in memory and by doing this you cast this address, which in turn is just an integer, to a character.
In this case the address of "0" just happens to be divisible by 256, which results 0.
Here is a quick example which I am too lazy to create in the playground:
#include <stdio.h>
int main()
{
int c = "0";
int c2 = "1"; // Different string to make sure the compiler doesn't optimize it to the same address as the first
printf( "0x%x, (char)0x%x\n", c, (char)c );
printf( "0x%x, (char)0x%x\n", c2, (char)c2 );
return 0;
}
In my case the output is
0x404000, (char)0x0
0x404002, (char)0x2
+ 1
perfect!