1

How can I create a array with dinamic size like this:

int sentLen = sentences.size();

double a[sentLen][sentLen];

for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a[i][j] = somefunction(i, j);
    }
}

My research led me to malloc which isn't recommended or other too complicated methods. After I realised that size must be constant, I tried using unordered_map, and I have tried the following:

std::unordered_map <int, int, double> a;


for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a.insert({ i, j, somefunc(i, j) });
    }
}

but still unsuccessful.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Deepsy
  • 3,769
  • 7
  • 39
  • 71
  • It depends on what you mean "dynamic size". Also there is nothing wrong with your first code block. – Daniel Apr 27 '14 at 02:42
  • @Daniel I'm getting `Expressions must have a constant value` with the first code. – Deepsy Apr 27 '14 at 02:45
  • 1
    What compiler and version are you using? Older compilers do not support variable length arrays. If your compiler doesn't support it, minimal research is required to [find the answer](http://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers). – Daniel Apr 27 '14 at 02:48

2 Answers2

1

You don't really want to use arrays.

std::vector<std::vector<double>> a{
   sentLen, std::vector<double>{ sentLen, 0.0 } };

for (int i = 0; i < sentLen; ++i)
{
    for (int j = 0; j < sentLen; ++j)
    {
        a[i][j] = somefunc(i, j);
    }
}
aschepler
  • 70,891
  • 9
  • 107
  • 161
  • Thanks for the idea. Tho seems there is syntax error, because I got it running like `std::vector> a(sentLen, std::vector(sentLen, 0.0));` – Deepsy Apr 27 '14 at 02:50
  • Based on his first example, I don't believe the OP really needs any of the functionality of a vector, other than being able to declare it of variable length. He should use array pointers and `new` the memory himself. Using a vector of vectors is overkill. – Daniel Apr 27 '14 at 02:50
  • @Deepsy Put a space between the end brackets `> >`. – David G Apr 27 '14 at 02:51
  • Using the `new` operator is generally a bad idea. – aschepler Apr 27 '14 at 02:52
  • The `{}` initialization is a C++11 feature. Your post looked like you were attempting to use it. If you use g++ or clang++, try the `-std=c++11` switch. – aschepler Apr 27 '14 at 02:53
1

You're getting an error because you can't use variables as static array sizes. They must be known at compile time. You have to allocate dynamically or use a vector instead.

David G
  • 94,763
  • 41
  • 167
  • 253