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.

8
  • 1
    int dp[len1][len2]={0}; is not allowed. Use std::vector Commented Dec 15, 2022 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 and start to learn properly the language. C++ is not a language you can learn just by try and guess. Commented Dec 15, 2022 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 Commented Dec 15, 2022 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++. Commented Dec 15, 2022 at 12:23
  • @MarekR OK, I will keep this in mind. Commented Dec 15, 2022 at 12:27

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

@rushabhvg you may want to consider C++ standard collections instead. I updated my answer just in case

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.