Can anyone help me assign value to the positions of this matrix with pointers?

Asked

Viewed 171 times

1

Hello, I am doubtful about the following code, it creates a two-dimensional matrix using pointers, the command line that should assign specific value to each position of the matrix seems not to work, because when writing on the screen appears numbers that I do not assign, anyone can help me assign value to positions of this array with pointers?

#include <stdio.h>
#include <stdlib.h>

int** alocarMatriz(int Linhas,int Colunas){ //Recebe a quantidade de Linhas e Colunas como Parâmetro

  int i=0,j=0; //Variáveis Auxiliares

  int **m = (int**)malloc(Linhas * sizeof(int*)); //Aloca um Vetor de Ponteiros

  for (i = 0; i < Linhas; i++){ //Percorre as linhas do Vetor de Ponteiros
       m[i] = (int*) malloc(Colunas * sizeof(int));    //Aloca um Vetor de Inteiros para cada posição do Vetor de Ponteiros.
        for (j = 0; j < Colunas; j++){ //Percorre o Vetor de Inteiros atual.
            m[i][j] = 0; //Inicializa com 0.
            printf("%d",m);
       }
       printf("\n");
  }
//return m; //Retorna o Ponteiro para a Matriz Alocada
}

int main(int argc, char *argv[]) {



    int Linhas, Colunas;

    printf("Entre com o numero de linhas:");
    scanf("%d",&Linhas);

    printf("\n\nEntre com o numero de linhas:");
    scanf("%d",&Colunas);


    alocarMatriz(Linhas, Colunas);

    return 0;
}

1 answer

0


The printf is not displaying the element you have just saved:

m[i][j] = 0; //Inicializa com 0.
printf("%d",m); //<---aqui

Switch to:

printf("%d",m[i][j]);

The m It’s a pointer to a pointer, not the number you just saved. To access the number you must specify the row and column, as well as the assignment of the 0.

If the function alocarMatriz is to be used in main must place the return m; that has commented, and change the call that has on main for:

int **matriz = alocarMatriz(Linhas, Colunas);

Do not forget that you also have to release the memory associated with the matrix when you no longer need it, through the function free

  • Thank you, I understood the pq of using the indices for writing the content of the matrix positions, thank you!!!

Browser other questions tagged

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