1

OK, this question seems to be silly but bear with me. When I trying to create a 2D array in C++, it gave me some warnings (len is an integer):

double a[len][len];
// warning: variable length arrays are a C99 feature
// warning: variable length array used

So I tried another:

double **a = new double[len][len];
// error: only the first dimension of an allocated array may have dynamic size
// read of non-const variable 'len' is not allowed in a constant expression

How can I do it correctly in C++11?

xiaoyu2006
  • 507
  • 7
  • 20
  • `std::vector> a(len, std::vector(len));` – PaulMcKenzie Dec 29 '19 at 03:12
  • Array dimensions MUST be constant. Some compilers will allow the first bit of code to be more C-like. It's a fabulous way to blow the top off the stack, though. If you don't know the dimensions ahead of the time, I recommend using [something more like this](https://stackoverflow.com/a/2076668/4581301). You still get contiguous storage, but it's in Dynamic storage where usually you have much more memory. – user4581301 Dec 29 '19 at 03:12
  • 1
    There are many ways to do this with different trade-offs. – Galik Dec 29 '19 at 03:14
  • 1
    Also [this answer may be helpful](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048) – PaulMcKenzie Dec 29 '19 at 03:29

2 Answers2

-1
double** a=new double*[len];
for(int i=0;i<len;++i)
{
   a[i]=new double[len];
}
error
  • 32
  • 3
  • Perhaps a note on the destruction part to make it replace the automatic `double a[len][len];` variable would be good. With that, the use of a smart pointer - and ultimately `std::vector` to replace all the cumbersome memory management. – Ted Lyngmo Dec 29 '19 at 03:18
  • I recommend covering the destruction logic for completeness because clean up for this option is non-trivial. – user4581301 Dec 29 '19 at 03:18
  • 3
    This is the worst way to allocate a dynamic 2D array that have a uniform number of columns. There are so many things wrong with it -- memory fragmentation, hard to diagnose an error if one of those `new[]` calls fail, etc. – PaulMcKenzie Dec 29 '19 at 03:24
  • @error [See this example](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048) – PaulMcKenzie Dec 29 '19 at 03:30
  • I'd upvote if you add the freeing of memory. – Felipe Gutierrez Dec 29 '19 at 03:35
  • @FelipeGutierrez This is a terrible replacement for `double a[len][len];` but freeing the memory would make it somewhat complete at least. – Ted Lyngmo Dec 29 '19 at 03:36
-2

Are there any restrictions on what you can use? If you're planning to do array manipulations I'd say just use [Eigen] (http://eigen.tuxfamily.org/index.php?title=Main_Page)

IanQ
  • 1,831
  • 5
  • 20
  • 29