-1

I want to initialize 2d array with default 0 values. rows and columns are dynamically changed values

int data[rows][columns] = { {}, {} };

And getting error

error: variable-sized object 'data' may not be initialized
   int data[rows][columns] = { {}, {} };

What I did wrong?

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • 1
    Does this answer your question? [variable-sized object may not be initialized c++](https://stackoverflow.com/questions/23751075/variable-sized-object-may-not-be-initialized-c) – Piglet May 19 '20 at 06:23
  • 2
    the problem is that your compiler does not know the values of rows and columns at compile-time. please note that dynamic memory allocation usually is not a good idea in MCUs, so you should have very good reasons to do that. I'm quite surprised that an experienced developer and SO member like you can't google error messages. ;) – Piglet May 19 '20 at 06:27
  • @Piglet , it is also possible that before there are `#define rows (6)` or something like that. The pre-processor will substitute `rows` with a number. We just do not know the code before. (however, it is just an hypothesis) – Leos313 May 19 '20 at 11:02
  • Very bad idea when you have only a few bytes of RAM. – TomServo May 19 '20 at 23:14

2 Answers2

0

Remove ''= { {}, {} }''

Since you can't add an entire array later down the sketch, I assume you insert it per row and per colum into the array.

Blobtech
  • 11
  • 1
0

As far as I know, and as explained here, If you do NOT use dynamic allocation (for example malloc), the values are automatically initialized to 0. So, simply:

#define rows (3)
#define columns (4)

//...

int data[rows][columns];

//...

int main(){ 
    //...
}

Please note that the value of rows and columns must be known at compile-time.

However, when you use malloc, you can iterate on the indices:

for(int i=0;i<rows;i++){
    for(int j=0;j<columns;i++){
        data[i][j]=0;
    }
}
Leos313
  • 5,152
  • 6
  • 40
  • 69