-8
auto data = new char[480][640][3]();
char data = new char[480][640][3]();

First works. Second doesnt. Why? Isn't auto supposed to just replace itself with the type of the initializer?

Moterius
  • 1
  • 1
  • 11
    Because `char` is not a pointer type. You don't need `auto` but you need a correct type. `new` returns a pointer. – François Andrieux Oct 21 '22 at 21:35
  • 1
    and if you are going multi-dimensional array mad - use a library. life will be a lot easier. – Neil Butterworth Oct 21 '22 at 21:38
  • I'm using this to store the image to display via OpenGL. Don't think a library's a good idea here. – Moterius Oct 21 '22 at 21:43
  • 1
    @Moterius Refer to a [good beginners book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) before asking trivia basics like this here please. That's definitely and explicitly unwanted. – πάντα ῥεῖ Oct 21 '22 at 21:46
  • 1
    3 D arrays are annoying. You can make [a really simple and safe 2D array](https://stackoverflow.com/a/36123944/4581301) out of a `vector` with the same syntax as a regular array, but to get the third dimension you have to start jumping through hoops with proxies or give up on `[]` and [use `operator ()`](https://stackoverflow.com/a/2076668/4581301). – user4581301 Oct 21 '22 at 21:55
  • Well this array is basically a screen buffer anyways [x][y][0|1|2] = [r|g|b], so I doubt that's necessary. – Moterius Oct 21 '22 at 22:06
  • You could make a 2D array of 1D arrays. That simplifies things a little. – user4581301 Oct 21 '22 at 22:10
  • `auto` is never *necessary*. It is a shortcut for convenience when the programmer can't (or doesn't want to expend the effort to) work out and explicitly code the actual type. In templates, it can simplify code a lot, but is still not necessary. In this case, the type of `data` needs to be `char(*)[640][3]`, not `char`. – Peter Oct 21 '22 at 22:14
  • `struct Display { std::byte buffer[480][640][3]{}; };` and `Display* display = new Display;` Also a convenient place to add member functions that operate on a display. – Eljay Oct 21 '22 at 22:25

1 Answers1

7

Because the type isn't char. The type is char(*)[640][3] and the declaration would be written as

char (*data)[640][3] = new char[480][640][3]();
user253751
  • 57,427
  • 7
  • 48
  • 90
  • And as pointed out above, 'new' returns a pointer instead of the actual object, meaning it wont cause the damn stackoverflow error that led me here in the first place. Makes sense now. – Moterius Oct 21 '22 at 21:45