0

I've tried many methods and this one is one of them:

void init_table(int _table[][MAX_COLUMNS]) {
    for (int i = 0; i < MAX_COLUMNS; i++) {
        for (int j = 0; j < MAX_ROWS; j++) {
            _table[i][j] = -1;
        }
    }
}

I am just trying to figure out how to initialize my array with -1 rather than 0 it defaults to.

TeachMeTWz
  • 41
  • 5
  • Arrays are pretty stupid. There isn't much you can do with them. Consider using [`std::array`](https://en.cppreference.com/w/cpp/container/array) and its [`fill` method](https://en.cppreference.com/w/cpp/container/array/fill). – user4581301 Sep 21 '21 at 23:17
  • Side note: arrays of `int` don't default to 0. They don't necessary default to anything specific. – user4581301 Sep 21 '21 at 23:18
  • 1
    You can iterators if you use [std::array](https://en.cppreference.com/w/cpp/container/array) or [std::vector](https://stackoverflow.com/a/1833146/421195): https://stackoverflow.com/questions/11400090/why-is-the-c-initializer-list-behavior-for-stdvector-and-stdarray-differen. Otherwise, you could try `memset(array, -1, sizeof(array[0][0]) * row * count)` – paulsm4 Sep 21 '21 at 23:19
  • **Sidenote:** your function takes a pointer to a (1D) array of int. To actually take a 2D array it should be `void init_table(int (&_table)[MAX_ROWS][MAX_COLUMNS])`. This might become important should you use `sizeof(_table)` at some point. – spectras Sep 22 '21 at 00:10
  • 1
    Given `int _table[][MAX_COLUMNS]` and `for (int i = 0; i < MAX_COLUMNS; i++)`, `_table[i][j] = -1;` is wrong. `i` should be in the second dimension. Also, when looping, prefer to have the row (first index) in the outer loop and the column (second index) in the inner loop. This is conducive to how memory caches commonly work. – Eric Postpischil Sep 22 '21 at 00:34
  • 1
    Clarify the question. To initialize an array with a value other than zero, one simply sets each element of the array to a desired value. Is your question about some failure you are getting doing this, such as one caused by the incorrect indexing noted above? Or are you asking what is an efficient way to do this? Or something else? – Eric Postpischil Sep 22 '21 at 00:35

1 Answers1

3

If you need to fill by the same value, use std::fill:

std::fill(_table, _table + MAX_ROWS*MAX_COLUMNS, -1);

Of course, if you use padding or other advanced techniques, you should take this into account and adjust your code, but this is more advanced topics and should be considered separately.

Damir Tenishev
  • 1,275
  • 3
  • 14