Matrix as a function parameter

I'm trying to create a function "matrix copy" (2 dimensions) that copies matrix1 to matrix2. I don't know the initial width(largura in portuguese) and height(altura in portuguese), they are defined on function main. When I try to compile the code it says that "largura" was not declared on the scope of function void copia_matriz. How should I pass the value for the width on the parameters of function void copia_matriz?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
include <iostream>

using namespace std;

void copia_matriz(int mat1[][largura], int mat2[][largura], int largura, int altura){
    for(int i=0;i<altura;i++)
        for(int j=0; j<largura; j++){
            mat2[i][j]=mat1[i][j];
        }
}
int main(){

    int largura, altura;
    cin >> largura >> altura;

    int mat1[altura][largura];
    int mat2[altura][largura];

    for(int i=0;i<altura;i++)
        for(int j=0;j<largura;j++)
            cin >> mat1[i][j];

    copia_matriz(mat1, mat2, largura, altura);

    for(int i=0;i<tamanho;i++)
        for(int j=0;j<largura;j++)
            cout << mat2[i] << " ";

    return 0;
}
you can only ever pass 1 unknown dimension.
for this reason among several good reasons, it is usually best to define a matrix (and other 2 & 3 D constructs) as one dimensional and access it manually, allowing you to pass it via
function (int *mat1, int *mat2 ...)

you can do it with vector of vector the way you are writing it for smaller matrices. single vector is still preferable in my eyes so you can reshape/transpose/block write to file/block copy /single loop iterate the data/ and more. You can typedef the double vector if you don't need a full blown class for it (this will help modify the code later if you change your mind about anything like moving to doubles or a class etc).
Last edited on
Topic archived. No new replies allowed.