The name of an array itself, where is it stored

前端 未结 4 1715
醉话见心
醉话见心 2021-01-20 16:37

How are the names of arrays stored in memory?

For example if I write:

char arr[10];

the array items are stored in memory starting f

4条回答
  •  没有蜡笔的小新
    2021-01-20 16:55

    If you mean the literal name that you declared it with, that is generally compiled out unless you compiled with debugging symbols -g.

    If you declared something on the stack, the machine code generally refers to the array elements as an offset from the frame pointer $ebp.

    To answer your implied question, for an array on the stack, it does not exist. The machine code does not know what arr is. It only knows that there is a region of memory that you are addressing using offsets (indices in your code).

    The question is more meaningful for an array on the heap, because now you have a pointer (which has its own address), and the memory which holds the actual array (which is on the heap, and stored inside the pointer).

    Consider the following code.

     char* arr = malloc(5);
    

    Assuming you compiled with debug symbols, if you look at &arr inside gdb, you will see the address where the pointer arr is stored.

    You can demonstrate the same thing if you create a separate pointer to an array on the stack.

     char arr[10];
     char* ptr = arr;
    

    Here, you will see that ptr has separate storage (p &ptr), and holds the address of arr as its value, but &arr itself is equal to the address of its first element.

提交回复
热议问题