Vincent Gable’s Blog

December 25, 2009

A C &Puzzler[]

Filed under: Announcement,Bug Bite,C++,Objective-C,Programming | , , ,
― Vincent Gable on December 25, 2009

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:

  1. Print “Joy!”
  2. Print garbage
  3. Print the same address for s
  4. Print the a different address for s
  5. Crash
  6. 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);

Explanation.

Powered by WordPress