[ale] This is legal C:

Geoffrey esoteric at 3times25.net
Thu Feb 12 10:55:33 EST 2004


Bjorn Dittmer-Roche wrote:
> Someone sent me this. It's an interesting oddity. Try it on your
> favorite C compiler!
> 
> 	bjorn
> 
> --------------------------------------------------
> 
> /* Find the strangeness! Spotted on kuro5hin... */
> #include <stdio.h>
> 
> char *foo[] = {"what", "the", "heck", "is", "this"};
> 
> int main(int argc, char **argv)
> {
>   int j=2;
>   printf("Test: %s\n", j[foo]);
>   return 0;
> }


In C, j[foo] is the same as *(j + foo).  foo alone is the address of the 
beginning of the array foo[].  When you add an int to an address, you 
actually are doing pointer math, thus you're saying give me the 2 entry 
in the array foo[].  That is:

take the address of the beginning of the array: foo

add 2 to it to give me the address of the 3rd item in the array (0,1,2)

The * says, give me the value found at that address point, which happens 
to be the string "heck" in the array.

-- 
Until later, Geoffrey                     Registered Linux User #108567
Building secure systems inspite of Microsoft



More information about the Ale mailing list