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

1
Hello, I am in doubt about the following code, it creates a two-dimensional array using pointers, the command line that should assign specific value to each position of the array does not seem to work, because when typing on the screen it appears numbers that I do not assign , can anyone help me to value the 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;
}
    
asked by anonymous 05.11.2017 / 01:03

1 answer

0

printf is not showing the element you just saved:

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

Switch to:

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

The m is a pointer to pointer, not the number you just saved. To access the number you have to specify the row and column, just as it is in the assignment of 0 .

If the alocarMatriz function is to be used in main you should put the return m; you have commented on, and change the call it has in main to:

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

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

    
05.11.2017 / 01:16