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})
12
  • 1
    What happened when you tried the code you shared? Commented Jun 26, 2020 at 13:27
  • 1
    in int x[row][col] the dimesnions row and col must be compile time constants, hence you already included the answer in the quesiton and it is not clear what you are asking for Commented Jun 26, 2020 at 13:27
  • 2
    perhaps: Why aren't variable-length arrays part of the C++ standard? Commented Jun 26, 2020 at 13:28
  • 1
    @idclev463035818 That doesn't work. Only one dimension can be unspecified. Commented Jun 26, 2020 at 13:36
  • 5
    @hipativ414, post your code, and the errors in the question, this game of trying to guess what you are doing is not a very effective way to solve your problem. Commented Jun 26, 2020 at 13:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.