-2
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)

kia
  • 1
  • 3
  • 1
    The contents of the memory create by `new` and `new[]` is not initialized. The elements in the array will have *indeterminate* values. And using such values (even printing them like you do with `std::cout << tt[0]`) leads to *undefined behavior*. – Some programmer dude Jan 22 '22 at 16:45
  • 5
    And it seems to me that you need to go back to your text-books and study some of the basic. If you don't have any text-books then please invest in [some good ones](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Jan 22 '22 at 16:47

2 Answers2

0

What is the difference between these two?

One is the value of the object in the array, and the other is the memory address of the object in the array.

I don't know why the two values ​​have different formats

The formats are different because the two values have different types. One is a double and the other is a pointer (double*).

P.S. Since you don't initialise the elements of the array, reading the value results in undefined behaviour. This is a bug. Don't ever do that.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

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.

digito_evo
  • 3,216
  • 2
  • 14
  • 42