2

I want to do something like:

int a[][];  // I know this code won't work, its to demonstrate what I want to do

void func(int n, int m){
    a = int[n][m];
}

that is, initialise a global array whose size depends on function input. If this array was local, it would be a trivial case, but I don't know how to do this in the case shown above. Any help would be very useful!

6
  • 4
    Make or get a matrix class that uses a 1d std::vector under the hood. That gives you the best performance and ease of use. Commented Dec 5, 2019 at 14:00
  • @NathanOliver-ReinstateMonica I got that, but is there any method that is strictly restricted to arrays? Commented Dec 5, 2019 at 14:02
  • 4
    Nope. An array's size must be known at compile time. If you only know the size at run time, you need dynamic allocation and you should use a std::vector to handle that for you. Commented Dec 5, 2019 at 14:03
  • 1
    You could make a a pointer into an array of pointers instead of an array of arrays. But initializing it and cleaning it up get a bit tricky, especially considering exception safety. Commented Dec 5, 2019 at 14:07
  • @NathanOliver-ReinstateMonica got it. Thanks! Commented Dec 5, 2019 at 14:18

3 Answers 3

1

You can create a matrix with std::vector:

std::vector<std::vector<int>> a;

void func(int n, int m) {
    a.resize(n);
    for(int i = 0; i < n; i++) {
        a[i].resize(m);
    }
}

Then you can access elements in the same way you do with int a[][]:

a[i][j] = number;
Sign up to request clarification or add additional context in comments.

Comments

1

One way to achieve this is to encapsulate a flat std::vector in a Matrix class and use math to get an element with row and column as in this example:

template<typename T>
class Matrix {
private:
    vector<T> vec;
//...
public:
    T& get_value(size_t const row, size_t const col) {
        return vec[row * col_count + col];
    }
};

Comments

0

you can try this

int ** a; // is a pointer of two dimension

void func(int n, int m){
    a = new int*[n]; //dynamic allocation global pointer a
    for(int i = 0; i < n; i++)
        a[i] = new int[m]();
}

2 Comments

Just no. new has no place here. It is dangerous and error prone and a lot worse than std::vector<std::vector<int>> a; void func(int n, int m){ a = std::vector<std::vector<int>>(n, std::vector<int>(m)); }
However your solution gets work but as @NathanOliver-ReinstateMonica said, it's better to use vector class

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.