Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a 2D array with same values in c++

WE can use fill_n function to initialize 1D array with value.

int table[20];
fill_n(table, 20, 100);

But how can we initialize 2D array with same values.

int table[20][20];
fill_n(table, sizeof(table), 100); //this gives error
like image 933
Devesh Agrawal Avatar asked Jun 26 '26 18:06

Devesh Agrawal


1 Answers

You can use a pointer to the first element and a pointer to one past the last one:

int table[20][20];
int* begin = &table[0][0];
size_t size = sizeof(table) / sizeof(table[0][0]);
fill(begin, begin + size, 100);
like image 176
juanchopanza Avatar answered Jun 29 '26 08:06

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!