Print data from a dynamically allocated two-dimensional array

4

I would like to know how I can print the information collected in Creator_Matrix using the Print function. This is the code I have made so far:

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

float **cria_matriz (int lin, int col){
    int **mat;
    int i = 0;
    int j = 0;
    mat = (int **) malloc (lin * sizeof (int));
    for (i = 0; i < lin; i++){
        mat[i] = (int *) malloc (col * sizeof (int));
    }
    for (i = 0;  i < lin; i++){
        for (j = 0;  j < col; j++){
            mat[j][i] = mat [i][j];
        }
    }
    return mat;
}

void imprime (int lin, int col, float **mat){
    printf("Valor na lin %d, coluda %d: ", lin, col, **mat);
}

int main (void){
    int lin = 0;
    int col = 0;
    printf("Digite o numero de linhas da matriz:");
    scanf("%d", &lin);
    printf("Digite o numero de colunas da matriz:");
    scanf("%d", &col);

    float **matriz = cria_matriz((int) lin, (int) col);
    imprime (lin, col, matriz);

    return(0);
}
    
asked by anonymous 19.03.2015 / 17:47

1 answer

5

Your imprime function must have a two-dimensional loop to be able to print all the elements one by one:

for (l = 0; l < linhas; l++) {
    for (c = 0; c < colunas; c++)
        printf("%.2f ", matriz[l][c]);
}

Here is a complete example:

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

float **cria_matriz(int linhas, int colunas) {
    float **matriz;
    matriz = (float**) malloc(linhas * sizeof(float));
    int x;
    for (x = 0; x < linhas; x++)
        matriz[x] = (float*) malloc(colunas * sizeof(float));
    return matriz;
}

void imprime(int linhas, int colunas, float **matriz) {
    int l, c;
    for (l = 0; l < linhas; l++) {
        for (c = 0; c < colunas; c++)
            printf("%.2f ", matriz[l][c]);
        printf("\n");
    }
}

int main(void) {
    float **matriz = cria_matriz(3, 2);
    int l, c;
    for (l = 0; l < 3; l++)
        for (c = 0; c < 2; c++)
            matriz[l][c] = l + c;
    imprime(3, 2, matriz);  
    printf("\n");
}
    
19.03.2015 / 17:53