-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?

4
  • 1
    Does this answer your question? variable-sized object may not be initialized c++ Commented May 19, 2020 at 6: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. ;) Commented May 19, 2020 at 6: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) Commented May 19, 2020 at 11:02
  • Very bad idea when you have only a few bytes of RAM. Commented May 19, 2020 at 23:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.