1

Possible Duplicate:
Accessing arrays by index[array] in C and C++

#include <stdio.h>
int main()
{       
    int a=3, b = 5;
    printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);
    printf(&a["WHAT%c%c%c  %c%c  %c !\n"], 1["this"],
    2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);

    return 0;
}

This is one of the practice problems that I was given in class. I'm trying to figure out how this code was able to get to the output, which is

Hello! how is this? super That is C !

The &a[" %s"] operation. How does that work? along with the seco

Community
  • 1
  • 1
Nopiforyou
  • 350
  • 1
  • 7
  • 20

2 Answers2

3

The code

&a["Ya!Hello! how is this? %s\n"]

Is interpreted as

&(a["Ya!Hello! how is this? %s\n"])

Since all C-style strings are pointers, this is a bizarre but legal usage of the fact that

arr[i]

and

i[arr]

are both legal in C. Consequently, the code should be interpreted as

&("Ya!Hello! how is this? %s\n"[a])

And since a = 3, this is the character H. Since we take the address of this character, this gives a pointer to the C-style string

"Hello! how is this? %s\n"

Using this as a starting point, you can try to decode the rest of the program.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Thank you! That helps. But could you just explain the arr[i] and i[arr] relation. Are you saying that arr[5] can be also 5[arr]? They are equivalent? – Nopiforyou Dec 12 '12 at 03:42
  • 1
    @Nopiforyou- Yep! `arr[i] = *(arr + i) = *(i + arr) = i[arr]`. – templatetypedef Dec 12 '12 at 03:43
  • Wow thank you. I can't help but wonder if this is common or rather an obscure part of C. I've definitely never seen it written this way before. – Nopiforyou Dec 12 '12 at 03:49
  • @Nopiforyou- This is ridiculously obscure. I teach a CS course and would never put something like this in it... you will almost never see code like this. – templatetypedef Dec 12 '12 at 03:49
  • 1
    @Nopiforyou: This is rare in real-life code, yet very well-known as a curiosity. Basically, this is a heavily overused C anecdote. – AnT stands with Russia Dec 12 '12 at 04:16
1

Firstly, you have to understand that string literal is an array of char elements. Which means that you can use string literal in the same way you would use any other array. This is a legal C expression

"hello"[i]

which will evaluate to the ith character of the string "hello". For example, "hello"[1] gives you access to character that stores e.

Secondly, you have to understand that in a legal a[i] expression a and i can be swapped without changing the meaning of the expression. This means that

i["hello"]

is also legal and also gives you access to the ith character of string "hello". So, if i is equal to 2, then i["hello"] refers to the first l.

Now, this is already sufficient to decipher the original code, assuming you know what printf is and how it works.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765