This doesn't look like a function. What is this?

前端 未结 5 1976
無奈伤痛
無奈伤痛 2021-01-06 05:02

A friend asked me to write a function in C to return the 100th element of an array. I\'m not very familiar with C, so I wasn\'t sure how to make a generic function that coul

5条回答
  •  广开言路
    2021-01-06 05:15

    This is the special funky way you can access arrays.

    Let's recall that arrays can be treated like pointers, and you can use arithmetic.

    For example:

    let x be some arbitrary array:

    int x[4];
    

    Implies accessing x's 5th element, which is *(x+4).

    Terrible example of memory layout:

    x -> [0][1][2][3][4]
    

    Now, the weird thing you can do with C arrays/pointers to blocks, is flip the number and variable in bracket notation.

    x[4] is equal to 4[x]
    

    Because they break down to:

    *(x+4) and *(4+x)
    

提交回复
热议问题