Is chars[4] and 4[chars] the same in C? Why?

This question already has an answer here:

  • With arrays, why is it the case that a[5] == 5[a]? 17 answers

  • In raw C, the [] notation is just a pointer math helper. Before [] , you'd look for the fourth char in the block pointed to by ptr like:

    *(ptr+4)
    

    Then, they introduced a shortcut which looked better:

    ptr[4]
    

    Which transaltes to the earlier expression. But, if you'd write it like:

    4[ptr]
    

    This would translate to:

    *(4+ptr)
    

    Which is indeed the same thing.


    Because a[b] is exactly the same as *(a+b), and + is commutatitve.

    chars[4] is *(chars+4) , and 4[chars] is *(4+chars)


    http://c-faq.com/aryptr/joke.html试试这个来测试编译:http://codepad.org/

    链接地址: http://www.djcxy.com/p/86722.html

    上一篇: 为什么2 [myArray]有效的C语法?

    下一篇: C中的chars [4]和4 [chars]是否相同? 为什么?