-1

I'm trying to declare a two-dimensional array in my class like so:

#pragma once

class Matrix
{
    float elements[][];
};

Except this isn't valid. If I get rid of the last two square brackets, it does work though. What do I need to change to be able to declare a two-dimensional array without initializing it?

Talha
  • 524
  • 1
  • 6
  • 22
liaquore
  • 403
  • 8
  • 22
  • You cannot create Variable Length Arrays in C++ (some compilers do allow it for one dimensional arrays, but it's non-standard). Use `std::vector>` instead. – Yksisarvinen Apr 07 '19 at 08:59
  • 2
    For plain arrays (2D or not) the size has to be known at compilation time. Use `std::vector` instead. – HolyBlackCat Apr 07 '19 at 09:00
  • If you need plain array, you need to state its size or alternatively use `float **elements;` which behaves very similarly to an array. Another option is to use `std::vector`. – Piotr Siupa Apr 07 '19 at 09:10
  • 2
    I would prefer a single `std::vector` for storage like proposed e.g. here: [SO: C++ Matrix Class](https://stackoverflow.com/a/2076668/7478597). – Scheff's Cat Apr 07 '19 at 09:12
  • @liaquore What should the size of the array be? – Michael Kenzel Apr 07 '19 at 09:17
  • Possible duplicate of [c++ declare an array of arrays without know the size](https://stackoverflow.com/questions/12830197/c-declare-an-array-of-arrays-without-know-the-size) – Talha Apr 07 '19 at 09:23
  • If you want a dynamic array you want `std::vector`. If you want a static array you want `std::array`. You never want a C-style array *except* when forced to by some other legacy code (and even then you can usually still use `vector` or `array`). – Jesper Juhl Apr 07 '19 at 09:41
  • "If I get rid of the last two square brackets, it does work though" - No, not really. VLAs (Variable Length Arrays) are *not* supported by standard C++. Some compilers support VLAs as an extension to the language, but that's not portable and you do not want to rely on it (in fact I would recommend you explicitly *disable* non-standard extensions in your compiler). – Jesper Juhl Apr 07 '19 at 09:45
  • If I use std::vector> how do I add an element to it? – liaquore Apr 07 '19 at 11:21

1 Answers1

3

No, it's not possible. You have to use dynamic allocation. Use std::vector<std::vector<float>> instead as @Yksisarvinen said.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Talha
  • 524
  • 1
  • 6
  • 22