How Are C Arrays Represented In Memory?

后端 未结 8 732
醉话见心
醉话见心 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 02:10

    A C array is just a block of memory that has sequential values of the same size. When you call malloc(), it is just granting you a block of memory. foo[5] is the same as *(foo + 5).

    Example - foo.c:

    #include 
    
    int main(void)
    {
        int foo[5];
        printf("&foo[0]: %tx\n", &foo[0]);
        printf("foo: %tx\n\n", foo);
        printf("&foo[3]: %tx\n", &foo[3]);
        printf("foo: %tx\n", foo + 3);
    }
    

    Output:

    $ ./foo
    &foo[0]: 5fbff5a4
    foo: 5fbff5a4
    
    &foo[3]: 5fbff5b0
    foo: 5fbff5b0
    

提交回复
热议问题