VansFannel
VansFannel

Reputation: 45921

Error initializing matrix with nembers of the same struct

I'm learning C++.

I only need a matrix and SPECIALLY how many rows and columns are in the matrix. I've though that I can use the following structure:

struct map {
    int rows;
    int columns;
    int matrix[rows][columns];
}

But, it doesn't compile. There is an error on line: int matrix[rows][columns];

I have also tried:

struct map {
    int rows;
    int columns;
    int matrix[map.rows][this.columns];
}

But, it doesn't compile.

The map.matrix will have map.rows and map.columns. I have declared this way because I don't know if I can declared without specifying its dimensions.

If it is correct to do: int matrix[][];.

What do I have to do to make the map.matrix have map.rows rows and map.columns columns?

Upvotes: 0

Views: 56

Answers (1)

mfnx
mfnx

Reputation: 3018

In order to create an array on the stack (i.e. not allocating it on the heap with new), the size of the arrays need to be known at compile time (your rows and columns are not known at compiletime).

Alternative 1: allocate on the heap (for big arrays which don't fit on the stack) or simply use vectors (vectors use heap memory).

Alternative 2: if you really need it to be on the stack, you could use a template class:

template <size_t ROWS, size_t COLUMNS>
class MyMatrix
{
    int _matrix[ROWS][COLUMNS];
};

Upvotes: 2

Related Questions