Amin
Amin

Reputation: 241

Initializing Error: How to create a multi dimensional zero array in C++

This code is written in C++ to make a multi dimensional array but it gives an initializing error. The size of array should be given by input console by the user and so it is not constant value. What is the problem and what is the solution? Thanks a lot.

#include <iostream>
using namespace std;
int main()
{
    int A , B ;
    cout << "A: " << endl;
    cin >> A ;

    cout << "B: " << endl;
    cin >> B ;

    int data[A][B] = {{0}};

return 0;
}

Upvotes: 1

Views: 55

Answers (1)

R Sahu
R Sahu

Reputation: 206697

The size of array should be given by input console by the user and so it is not constant value.

This is not possible in C++. A suitable replacement for using arrays is using std::vector. You can use:

int A = 10, B = 4;
std::vector<std::vector<int>> data(A, std::vector<int>(B, 0));

If you are using a pre-C++11 compiler, you'll need to have a space between the two >>.

std::vector<std::vector<int> > data(A, std::vector<int>(B, 0));

Upvotes: 1

Related Questions