Here’s a C-puzzler for you!
given this function,
void foo(char* s){ printf("s is at: %p\n s is: '%s'\n", s, s); }
and that
char s[] = "Joy!"; foo(s);
prints out
s is at:
0xbffff46b
s is: ‘Joy!’
what will this next line print?
foo(&s); //WHAT WILL THIS DO?
Pick all that apply:
- Print “Joy!”
- Print garbage
- Print the same address for
s
- Print the a different address for
s
- Crash
- Go into an Infinite loop
Answer
Answer: one and three
Yeah, it’s not what I expected either, especially since:
@encode(__typeof__(s)) = [5c] @encode(__typeof__(&s)) = ^[5c]
In fact, all of these are equvalent (modulo type warnings):
foo(s); foo(&s[0]); foo(&(*s)); foo(&s);
I’m guessing 1. should say “prints ‘Joy!'”, as otherwise the compiler has a sense of humour.
Comment by Max Howell — December 30, 2009 @ 10:24 pm
Oops! Yes, it should. (Although sometimes compilers do crack wise.)
Comment by Vincent Gable — December 31, 2009 @ 3:28 am