user3053042
user3053042

Reputation: 97

How to create a function in c++ that has a matrix's size determined by a parameter?

void prob6 (int n)
{
    int f,c,z=0, mat[n][n]; //error because of mat[n][n]
    for(int f=1;f<=n;f++)
    {
       z=f*n;
       for(int c=1;c<=n;c++)
       { ............

I am creating various number patterns in matrices, where their dimensions are [n][n] (square).

Upvotes: 0

Views: 80

Answers (1)

Blob
Blob

Reputation: 569

You can't statically allocate a variable amount of memory. You may want to allocate memory on the heap. You also need to remember to delete them when you're done. This is tedious, so use a std::vector.

std::vector<std::vector<int>> myVector; //Vector inside vector.

(Note the space between the two ">"s. >> is a different operator)

A simple example of vector can be found at: http://en.cppreference.com/w/cpp/container/vector/push_back

More: http://en.cppreference.com/w/cpp/container/vector

Upvotes: 1

Related Questions