Why does this work? Illogical array access

后端 未结 1 1783
情歌与酒
情歌与酒 2021-02-01 13:51

A friend of mine is learning C++ for the first time, and sent me this snippet:

int foo[] = { 3, 38, 38, 0, 19, 21, 3, 11, 19, 42 };
char bar[] = \" abcdefghijklm         


        
相关标签:
1条回答
  • 2021-02-01 14:32

    In simplistic terms, the access of an array element in C (and in C++, when [] isn't overloaded) is as follows:

    x[i] = *(x + i)
    

    So, with this and a little bit of arithmetic...

      foo[i][bar]
    = (foo[i])[bar]
    = (*(foo + i))[bar]
    = *((*(foo + i)) + bar)
    = *(bar + (*(foo + i)))
    = bar[*(foo + i)]
    = bar[foo[i]]
    

    Don't use this "fact" though. As you've seen, it makes the code unreadable, and unreadable code is unmaintainable.

    0 讨论(0)
提交回复
热议问题