4

In 3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?

What does 3["XeoPhoenix"] mean?

Halle
  • 3,584
  • 1
  • 37
  • 53
Michael
  • 43
  • 2

3 Answers3

6

3["XoePhoenix"] is the same as "XoePhoenix"[3], so it will evaluate to the char 'P'.

The array syntax in C is not more than a different way of writing *( x + y ), where x and y are the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without changing the meaning of the expression.

So 3["XeoPhoenix"] is compiled as *( 3 + "XeoPhoenix" ) where the string decays to a pointer and 3 is added to this pointer which in turn results in a pointer to the 4th char in the string. The * dereferences this pointer and so this expression evaluates to 'P'.

"XeoPhoenix"[ 3 ] would be compiled as *( "XeoPhoenix" + 3 ) and you can see that would lead to the same result.

x4u
  • 13,877
  • 6
  • 48
  • 58
5

3["XeoPhoenix"] is equivalent to "XeoPhoenix"[3] and would evaluate to the 4th character i.e 'P'.

In general a[i] and i[a] are equivalent.

a[i] = *(a + i) = *(i + a) = i[a] 
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 2
    Strange feature and it made it to the top of the list: http://stackoverflow.com/questions/1995113/strangest-language-feature/1995156#1995156 – codaddict Jun 03 '11 at 15:47
0

In C, arrays are very simple data structures with consecutive blocks of memory. They therefore need to be integers as these indices are nothing more than offsets to addresses in memory.

SamT
  • 10,374
  • 2
  • 31
  • 39