0

How can I initialize array with variables like int x[row][col];

int myArray[7][4] = { {1,2,3,4}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8} };

i want to initialize array as this =

int myarray({2,3,4},{12,4,5},{2,2,2})
hipativ414
  • 19
  • 5

1 Answers1

1

The exact answer is you cannot initialize an array like that, i.e., without providing both row and col at compile time, though std::vector can do the job for you.

You can use some code like this:

#include <iostream>
#include <vector>

void print_vector(std::vector<int> &v) {
    std::cout << "{ ";
    for (auto &&i : v) {
        std::cout << i;
        if (&i != &v.back()) {
            std::cout << ",";
        }
    }
    std::cout << " }";
}

void print_matrix(std::vector<std::vector<int>> &v) {
    std::cout << "{ ";
    for (auto &&i : v) {
        print_vector(i);
        if (&i != &v.back()) {
            std::cout << ", ";
        }
    }
    std::cout << " }" << std::endl;
}

int main() {
    std::vector<std::vector<int>> v = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; 
// same as std::vector<std::vector<int>> v({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}});
    print_matrix(v);
// prints { { 1,2,3,4 }, { 5,6,7,8 }, { 9,10,11,12 } } on stdout
}

I have included print_vector and print_matrix since the OP asked about them in the comments, though without thinking much about them. You can get better implementations on this thread.

brc-dd
  • 10,788
  • 3
  • 47
  • 67