0

in the online course from my university I met the next interesting fact:

The executing of the next line will produce '\0':

5["Peklo"]

I also tried some different examples by passing different integers and string literals. I know that C strings are const char * pointers therefore that code is valid and will compile, but I can not figure out how the output calculates/depends on the passing integer value of the string indexer. If someone knows, can you explain to me in detail why 0["P"], 0["A"] and 1["A"] produces different results (80, 65, 0)?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jeidoz
  • 54
  • 9
  • 1
    Does it help if I tell you that `a[b]` is the same as `b[a]`? i.e. `5["Peklo"]` is the same as `"Peklo"[5]` – Kevin Jan 07 '22 at 18:01
  • 1
    The expression `a[i]` is defined as `*(a + i)` - given an address `a`, offset `i` elements and dereference the result. Addition is commutative: `a + i == i + a`, so `a[i] == *(a + i) == *(i + a) == i[a]`. – John Bode Jan 07 '22 at 18:03
  • @JohnBode `float a[] = { NAN,NAN,NAN,NAN}; if(a[3]!=3[a]){puts("False");}` will print `False`. `a[i] == *(a + i) == *(i + a) == i[a]` is not always true. What is always true is that `&(a[i]) == &(*(a + i)) == &(*(i + a)) == &(i[a])`, as long as no UB is involved. – 12431234123412341234123 Jan 07 '22 at 18:22
  • @JohnBode well, now it makes sense... I did not look from that perspective. – Jeidoz Jan 07 '22 at 18:25

1 Answers1

2
5["Peklo"]  === "Peklo"[5] == (char[]){'P','e','k','l','o','0'}[5] == 0 == '\0'
                                       [0] [1] [2] [3] [4] [5]
0___________
  • 60,014
  • 4
  • 34
  • 74