1
bool vizitat[60][60];

...

if(/*some condition*/)
{
    vizitat[n][m] = {0}; // set all the elements to `false`.
    /*other code here*/
}

Is there a way of setting every element of vizitat to 0, ideally without an explicit loop?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Victor Zarzu
  • 41
  • 1
  • 9
  • `memset(vizitat, 0, sizeof vizitat);` is one way – john Mar 08 '19 at 08:27
  • 4
    As for your problem, please read about [`std::fill`](https://en.cppreference.com/w/cpp/algorithm/fill) and [`std::memset`](https://en.cppreference.com/w/cpp/string/byte/memset). Or just initialize it at definition with e.g. `bool vizitat[60][60] = { { false } };` – Some programmer dude Mar 08 '19 at 08:28
  • I was just reading out of curiosity and I found out I did not know that worked lol! @Someprogrammerdude Thanks for the knowledge! – M.K Mar 08 '19 at 08:43

1 Answers1

2

Since vizitat is declared as bool vizitat[60][60];,

std::fill(
    &vizitat[0][0]/*the first element*/,
    &vizitat[0][0] + sizeof visitat / sizeof(bool) /*one after the last element*/,
    false
);

would do it.

This is because the data in the array are contiguous. Using std::memset is not safe in general although a compiler might optimise to that.

Note that this approach would not work if the memory was allocated, say, row-by-row. For more details see How are multi-dimensional arrays formatted in memory?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    note: `memset` on bools is not safe. There could be some architecture where, in memory, `false = -1` and `true = 0`. And `sizeof(bool)` need not be 1. But this would probably work. I would do `std::fill(&vizitat[0][0], &vizitat[0][0] + (sizeof vizitat / sizeof(bool)), false)`, which would `memset` on most systems anyways. – Artyer Mar 08 '19 at 08:44