Dynamic matrix as parameter in C or C++?

Asked

Viewed 1,212 times

1

After hours of searching, I didn’t find anything that would answer my question, or I couldn’t understand the answer. I want to create a matrix NxN variable size. I made with pointers,but I want to pass it as a parameter between functions, one function to fill, another to manipulate, etc. But it’s not working

After creating the matrix, how do I pass it to another function? And how should the declaration of the other function be to receive it?

int main()
{
int **campo;
...
campo = alocaMatriz(altura,largura);
popularMatriz(campo); //???e agora rsrs
outraFuncao(campo);//??!?!?!
}

int alocaMatriz(int linha, int coluna)
{
int i,j;
int **campo = (int**)malloc(linha * sizeof(int*)); 

for (i = 0; i < linha; i++)
{
    campo[i] = (int*) malloc(coluna * sizeof(int)); 
    for (j = 0; j < coluna; j++)
    {
        campo[i][j] = 0; //Inicializa com 0.
    }
}
campo[0][0]=1;//adiciona o agente ao tabuleiro
}
outraFuncao(int **campo){} //?????
  • 1

    Use the linear matrix vector representation. and pass through a single pointer (int *field). dai to regain position would be using field[i+row*j], and allocation would be (int*) malloc(row * column * sizeof(int));

  • So I don’t need a double pointer? I didn’t understand very well...whenever I went to allocate matrices I did this way x.x buguei

  • 1

    Double pointer does not mean an Array. is a Pointer to a Pointer. If you think about how an array is implemented in memory, you’ll see that when it arrives at the end of a row, it jumps to the next row in the first column

  • Possible duplicate of Pass matrix as function parameter?

1 answer

1

The argument for the functions should be of type 'int **', if you are using a pointer-to-pointer representation. As a rule, the argument for the function must be of the same type as the data structure being passed, in this case a pointer to integer pointer.

Example:

void popularMatriz(int **campo);

int main(){
    int **campo = alocaCampo(linhas, colunas);
    popularMatriz(campo);
}
  • man, thanks! solved the problem kkk thanks.

  • Oops, you might want to mark that answer as right, so ;-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.