How Are C Arrays Represented In Memory?

后端 未结 8 708
醉话见心
醉话见心 2020-12-14 01:33

I believe I understand how normal variables and pointers are represented in memory if you are using C.

For example, it\'s easy to understand that a pointer Ptr will

8条回答
  •  一整个雨季
    2020-12-14 01:57

    An array is a block of contiguous objects with no spaces in between. This means that x in your second example is represented in memory as:

    +---------------------+-------------+---------+
    | Variable Name       | Address     | Value   | 
    +---------------------+-------------+---------+
    | x                   | 10568       | 12      |
    |                     |             +---------+
    |                     |             | 13      |
    |                     |             +---------+
    |                     |             | 14      |
    |                     |             +---------+
    |                     |             | ??      |
    |                     |             +---------+
    |                     |             | ??      |
    +---------------------+-------------+---------+
    

    That is, x is five ints big, and has a single address.

    The weird part about arrays isn't in how they're stored - it's how they're evaluated in expressions. If you use an array name somewhere that it isn't the subject of the unary & or sizeof operators, it evaluates to the address of its first member.

    That is, if you just write x, you will get a value 10568 with type int *.

    If, on the other hand you write &x, then the special rule doesn't apply - so the & operator works like it normally does, which means that it fetches the address of the array. In the example, this will be a value 10568 with type int (*)[5].

    The reason that x == &x is that the address of the first member of an array is necessarily equal to the address of the array itself, since an array starts with its first member.

提交回复
热议问题