Search code examples
c++dynamic-arraysmemory-address

memory address of dynamic array


double *tt;
tt = new double[2];
std::cout << tt[0] << std::endl;
std::cout << tt << std::endl;

The result is like this

-1.72723e-77

0x12e6062e0

What is the difference between these two? I don't know why the two values ​​have different formats (tt[0] is X.~~ but tt there is no point)


Solution

  • tt[0] is dereferencing the pointer to the array tt and the result is an expression of type double. It is equivalent to *tt. There is a random value in that location so you see a random floating-point value being printed.

    But tt is just a pointer (of type double*) and thus when you print it, the address of a memory location (the address of the first byte of the array) is displayed. C-style arrays automatically decay into a pointer.