0
String output
Can someone explain the output of the code below , which is âworldâ This was posted as one of the C quiz questions. #include <stdio.h> Int main() { printf( 4 + âwestworldâ); return 0; }
3 Answers
+ 2
string "westworld" has type char*, it is just a pointer to the first symbol of the string. string represented as array of chars with zero at the end which is appended by compiler automatically.
This string is represented as follows:
0 1 2 3 4 5 6 7 8 9
['w', 'e', 's', 't', 'w', 'o', 'r', 'l', 'd', 0];
^ pointer contains address of 'w'.
when you add 4 to that pointer you just offset the pointer 4 bytes forward to the char with index 4:
0 1 2 3 4 5 6 7 8 9
['w', 'e', 's', 't', 'w', 'o', 'r', 'l', 'd', 0];
^ pointer now contains address of 'w'.
printf just output a string (till zero char).
+ 1
thanks, just a fickle code.
0
C function
int printf(const char *format, ...)Â looks like this.
So your expression is treated like a pointer to where "westworld" is stored and by adding 4 to it you just move the starting point.
It is pointer arithmetic.
If you add 1 it will print estworld
2 stworld
...and so on....
Not sure if it's the complete explaination I am not that proficient in C.