Pointer Stew (was Re: Explanation, someone??)

Jim Lewis jwl at sag4.ssl.berkeley.edu
Sun Jun 16 08:34:27 AEST 1991


In article <33641 at usc.edu> burzin at skat.usc.edu (Burzin N. Engineer) writes:
>Hi,
>	I just gave an interview which had a C quiz and there was this program
>that really confused me. I have compiled the program and can still not figure
>out what is going on. Any reference or help will be appreciated.
>---
>char *c[] = {
>  "ENTER",
>  "NEW",
>  "POINT",
>  "FIRST"
>  };
>char **cp[] = { c+3, c+2, c+1, c};
>char ***cpp = cp;
>main()
>{
>  printf("%s", *++cpp);
>  printf("%s", *--*++cpp+3);
>  printf("%s", *cpp[-2]+3);
>  printf("%s\n", cpp[-1][-1]+1 );
>}
>
>When run it produces:
>ERSTEW

Part of the reason this quiz question didn't make much sense is because
it has a bug in it.  The first string printed should be **++cpp, not *++cpp.
The output will then be "POINTERSTEW".  Without the missing pointer dereference,
it's taking a piece of memory that holds a pointer, and trying to print
that sequence of bytes as a string.  On your architecture, the first byte
of the pointer was probably zero, which is the end-of-string marker, so
the first printf was a no-op.  Under a different byte ordering, you
might have seen some garbage characters, or perhaps a core dump.

I won't spoil the puzzle for you...you should go back to your C reference
and re-read the sections on arrays and pointers until you see what's
going on.

It's good to be able to understand what's going on with these programs,
but I'd be pretty leery of an employer that relied heavily on
these kinds of quiz questions to test someone's knowledge of C.  (I could
see one or two questions like this to seperate the truly outstanding
candidates from the merely competent, but a whole test like that? *shudder*!)

Both problems (including the POINTER STEW bug)  came from "The C Puzzle
Book" by Alan R. Feuer.   This isn't the first time they've been mentioned
on the net by people who ran across them at interviews....maybe the companies
who are using this book to test programmers should wise up and switch to
winners (or losers!) of recent Obfuscated C contests!

-- Jim Lewis,  U.C. Berkeley
   Center for EUV Astrophysics



More information about the Comp.lang.c mailing list