0

I was solving an algorithm and everything worked on my computer, the answer result is as what the question is saying

Main.cpp: 5:15: error: variable-sized object may not be initialized
        int array_2d [r] [c] = {{1, 5, 6},
                     ^ ^

Is there anything I could do to fix this? I am somewhat new to the algorithm solving challenges that are on the websites.

#include<iostream>
using namespace std;
int main(){
    int c=3,r=3;
    int array_2d[r][c]={{1, 5, 6},
                        {8, 2, 7}, 
                        {3, 4, 9}};
    int sum_row[c*r];
    int sum_col[c*r];
    int Max_total;

    int num_digit=2;
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            if(array_2d[i][j+1])
            {
                sum_row[i*c+j]=array_2d[i][j]*10+array_2d[i][j+1];
            }else{
                sum_row[i*c+j]=array_2d[i][j];
            }   
        }
    }
    for(int i = 0;i < 9; ++i) {
        if(sum_row[0] < sum_row[i]){
        sum_row[0]=sum_row[i];
        }
    };
        for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            if(array_2d[j+1][i]){
                sum_col[i*c+j]=array_2d[j][i]*10+array_2d[j+1][i];
            }else{
                sum_col[i*c+j]=array_2d[j][i];
            }
        }
    }
    for(int i = 0;i < c*r; ++i) {
  
    if(sum_col[0] < sum_col[i])
      sum_col[0]=sum_col[i];
    }
    if(sum_row[0] > sum_col[0]){
        Max_total=sum_row[0];
    }
    else{
        Max_total=sum_col[0];
      }
    cout<<"Max "<<Max_total<<endl;                      
}
Nirl
  • 3
  • 3
  • 1
    `int c=3,r=3;` should be `const int c=3,r=3;` or `constexpr int c=3,r=3;`. Sizes of arrays must be compile-time constants in standard C++. – user17732522 Mar 17 '22 at 07:46
  • It's hard to tell for sure without knowing how you compiled it on your computer and how the test site is compiling it. For starters: `int array_2d[r][c]` is [not part of standard C++](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard), so right there you have something non-portable. Making `r` and `c` `const int` though would address that. Beyond that, though, you _immediately_ exhibit undefined behavior by going outside the bounds of your array. When `j = c - 1`, `array_2d[i][j+1]` i.e. `array_2d[i][3]` is one over the limit. – Nathan Pierson Mar 17 '22 at 07:47
  • Hurray for the compiler giving this error. Too many new programmers who use those dodgy websites to "learn" C++ write this invalid syntax, and unfortunately, the compiler used at those websites accepts the invalid code. Then they post here, thinking that the code written is valid C++. – PaulMcKenzie Mar 17 '22 at 07:56
  • `int sum_row[c*r]; int sum_col[c*r];` -- This is also not legal C++ syntax, all due to what was pointed out earlier. If you want a dynamic array in C++, use `std::vector`. – PaulMcKenzie Mar 17 '22 at 07:59

0 Answers0