0

Is there a way to initialize all items in a 2d array with console-inputted dimensions to a specified item without looping in C++? For example, say I have two integers, x and y, and a 2d array called grid:

#include <iostream>

int main() {
    int x, y;
    std::cout << "Enter the dimensions of the array separated by a space: ";
    std::cin >> x >> y;
    bool grid [x][y] {/*all false*/};
    // other code
    return 0;
}

Is there any way to initialize every item in grid in the format above? I tried:

    bool grid [x][y] {false};

but that just set the first item to false.

LogicalX
  • 95
  • 1
  • 10
  • 5
    Do note that variable lenght arrays [are not part of C++ standard](https://stackoverflow.com/q/1887097/6865932) though some compilers allow its use. – anastaciu Jun 20 '20 at 00:55
  • 2
    "but that just set the first item to false." --> are you sure? I'd expect that do to initialize the first to `false` and all elements to initialize to their default values. – chux - Reinstate Monica Jun 20 '20 at 01:01
  • @chuxReinstateMonica Yes, when I used that syntax and printed the values of the array there were all kinds of numbers besides 0. When I changed the values using a ```for``` loop, every item was 0 as I expected, so the code I wrote above doesn't work. – LogicalX Jun 20 '20 at 01:06
  • 1
    @anastaciu what you say seems to be what's causing the problem. With hardcoded dimensions, the above code works. I'll change that. Thanks! – LogicalX Jun 20 '20 at 02:42
  • @NotMyAccount If you make the dimensions hardcoded you need to make `grid` big enough to hold the biggest `x` and the biggest `y` the user is allowed to specify, even if the user only wants a `1 x 1` grid. That's not good. When the dimensions are not known at compile time, use a `std::vector`. – Ted Lyngmo Jun 21 '20 at 09:20
  • 1
    @tedlyngmo Okay, thanks for the tip! However, for my purposes, hardcoding the array size is fine because this is for a previous contest problem I'm doing for practice and the inputs are given through the console, and there are limits to how big the dimensions will be. I'll use vectors if I run into a similar situation in the future, though. Thanks! – LogicalX Jun 21 '20 at 13:19

5 Answers5

1

Variable length arrays is not a standard C++ feature. Moreover even in C where vaeiable length arrays are included in the Standard nevertheless you may not initialize them in declaration.

In C++ you should use the standard class template std::vector.

For example

int x, y;
std::cout << "Enter the dimensions of the array separated by a space: ";
std::cin >> x >> y;
std::vector<std::vector<bool>> grid( x, std::vector<bool>( y ) );

The last statement declares a vector of vector all elements of which will be set to false.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • However, there are some drawbacks to this approach: the 2-D array is not contiguous in memory, there are multiple separate memory allocations, and the syntax for declaring the 2-D vector is a little messy. I'd be tempted to use a single std::vector and manually index into it - perhaps all wrapped in a class to hide the details. – Eric Backus Jun 22 '20 at 16:51
  • @EricBackus There is no any drawback. It is possible to speak about drawbacks only in the context of a concrete application. So using a single vector with calculating indices as for a vector of vectors can be very error prone and be a big drawback. – Vlad from Moscow Jun 22 '20 at 18:38
0

You can use memset. You can read more about it here

What it does is it sets the block of memory that you specify to what you pass.

bhristov
  • 3,137
  • 2
  • 10
  • 26
0

bool grid [x][y] when x and y are not constexpr makes grid a VLA (Variable Length Array). VLA:s do not exist in standard C++ and are only available as an extension in some compilers. I suggest that you do not use them. Side note: You usually want to swap x and y since arrays are stored in row major order in memory and access to elements if you access them row-by-row is likely to be faster because of how caches work.

The idiomatic way is to use a std::vector.

#include <iostream>
#include <vector>

int main() {
    size_t x, y; // a suiteable unsigned type

    std::cout << "Enter the dimensions of the array separated by a space: ";
    std::cin >> x >> y;

    // create a 2D vector, all initialized to "false"
    std::vector<std::vector<bool>> grid(y, std::vector<bool>(x, false));  

    for(size_t yval = 0; yval < grid.size(); ++yval) {
        for(size_t xval = 0; xval < grid[yval].size(); ++xval) {
            std::cout << grid[yval][xval];
        }
        std::cout << '\n';
    }  
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

yes, you can initialize using memset.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int row=5;
    int col=6;
    int mat[row][col];
    memset(mat, 0, sizeof(mat[0][0]) * row * col);
    
    return 0;
}
-1
  • If you really want the values to be false, you can use bool grid[x][y] = {};. This works because the braces give a list of initial values, and when this is done then all remaining values in the array are zero initialized, which will give a value of false. Note: this is valid C++, but C does not allow an empty initialization list, so for plain C you would need bool grid[x][y] = {false};.
  • As bhristov mentions above, you can use memset. But this is not good c++ style in my opinion.
  • You can use std::fill or std::fill_n, because the 2-D array is a contiguous set of values of length x * y. This has the advantage of allowing you to specify other values than just false.
Eric Backus
  • 1,614
  • 1
  • 12
  • 29
  • This works. However, if what you said in the first point is true, then when I set the first item to ```false``` with ```{false}```, why didn't the rest of the values initialize to false as well? – LogicalX Jun 20 '20 at 01:10
  • Actually I think your original code should have worked. Note that my answer used an `=` sign, while your original code did not, but it don't think it should have made any difference. Is it possible that the variable-length arrays have different behavior? – Eric Backus Jun 20 '20 at 01:19
  • Variable length arrays are not valid C++. They are provided by a non-standard compiler extension, so it is entirely possible for them to behave differently. – eesiraed Jun 20 '20 at 02:34
  • @EricBackus when incorporating your answer into my code I didn't use "=" and it still worked. – LogicalX Jun 20 '20 at 02:36
  • @BessieTheCow That seems to be true. When I try my malfunctioning code with hardcoded dimensions, it works. – LogicalX Jun 20 '20 at 02:40