1

I am trying to initialize a 2d array (matrix) to 0 but, cant do it:

int longestCommonSubsequence(string text1, string text2) {
    int len1=0;
    len1=text1.length()+1;
    int len2=0;
    len2=text2.length()+1;
    int dp[len1][len2]={0};

Error:

Line 8: Char 16: error: variable-sized object may not be initialized
        int dp[len1][len2]={0};
               ^~~~
1 error generated.

I want initialize the matrix while declaring it. I do not want to use for loop.

rushabhvg
  • 88
  • 1
  • 12
  • 1
    `int dp[len1][len2]={0};` is not allowed. Use `std::vector` – 463035818_is_not_an_ai Dec 15 '22 at 12:20
  • 4
    Variable length array are not standard C++. Moreover, you can't just initialize to zero all the values by just assigning the whole array with zero. I'd suggest you to get a [good C++ book](https://stackoverflow.com/a/388282/11455384) and start to learn properly the language. C++ is not a language you can learn just by try and guess. – Fareanor Dec 15 '22 at 12:20
  • if `int dp[len1][len2];` did compile without error, then you are using a compiler extension. If you want to stay with it you need to read your compilers manual. However, its not really recommended, rather aim to write portable code – 463035818_is_not_an_ai Dec 15 '22 at 12:23
  • VLA is not part of C++ standard. This is possible since C has such feature and by default compiler allows to mix C with C++. – Marek R Dec 15 '22 at 12:23
  • @MarekR OK, I will keep this in mind. – rushabhvg Dec 15 '22 at 12:27
  • what compiler are you using? for gcc i suggest to use `-pedantic-errors` at least until you know what you are doing – 463035818_is_not_an_ai Dec 15 '22 at 12:29
  • You're using a VLA (an array with dimension that is not a compile-time constant). A multi-dimensional VLA at that. VLA's are not part of standard C++ at all. If your compiler supports VLA's *at all* it is as a non-standard extension. Let alone what it allows you to do with them (e.g. initialising elements on declaration). Instead of using a VLA, use `std::vector`. In your case, `std::vector > dp(len1, std::vector(len2, 0))` will be one way of declaring and initialising as you wish. – Peter Dec 15 '22 at 12:30
  • Umm, I was solving a coding problem on a website! – rushabhvg Dec 15 '22 at 12:31

1 Answers1

2

Variable sized arrays are not standard C++, for arrays of constant length you just use value-initialisation syntax:

int arr[4][4]{};

Alternatively, use C++ collections of variable length:

int rows = 4;
int columns = 4;
std::vector<std::vector<int>> vec(rows, std::vector<int>(columns));
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49