Why are `&array` and `array` pointing to the same address?

后端 未结 2 465
感动是毒
感动是毒 2020-12-29 02:03

Until now, I thought an array is the same as a pointer. But I found a weird case:

code

int array[5] = { 10,11,12,13,14};

std::cout << array          


        
2条回答
  •  滥情空心
    2020-12-29 02:54

    An array of X's has to behave like a pointer to a contiguous list of X's in memory much like a pointer. However, nowhere is it written where the memory that stores that data is must be it's own address and writablej. In the case of an explicit pointer there is a new allocation for this address (in this case the stack) however for an array, on the stack, the compiler already know where the contents are so no new allocation is needed.

    As a consequence, its not safe to treat it as a pointer, without indexing. e.g.:

    pArray = nullptr; // This is a memory leak, unless a copy is taken, but otherwise fine.
    array = nullptr; // This is will make the compiler upset
    

提交回复
热议问题