Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save santiagosilas/3ea623a5e6b553a066a51f9f02952bca to your computer and use it in GitHub Desktop.

Select an option

Save santiagosilas/3ea623a5e6b553a066a51f9f02952bca to your computer and use it in GitHub Desktop.
ANSI C - Alocação Dinâmica de Matrizes - Exemplo com Funções
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int **CriarMatriz(int L, int C){
// Aloca as linhas da matriz
int **m = calloc(L, sizeof(int *));
// Aloca as colunas da matriz
int i, j;
for(i=0; i < L; i++)
m[i] = malloc(C * sizeof(int));
return m;
}
void InicializarMatriz(int **m, int L, int C){
int i, j;
// Inicializa a matriz
srand(42);
for(i=0; i< L; i++)
for(j=0; j < C; j++)
m[i][j] = 10 * (i+1) + rand() % 10;
}
void ImprimirMatriz(int **m, int L, int C){
// Imprime a matriz
int i, j;
for(i=0; i< L; i++){
for(j=0; j < C; j++)
printf("%d\t", m[i][j]);
printf("\n");
}
}
void LiberarMatriz(int **m, int L ){
int i;
// Desaloca a memória
for(i=0; i < 5; i++)
free(m[i]);
free(m);
}
int main(void)
{
int i, j;
int **m = CriarMatriz(5, 4);
InicializarMatriz(m, 5, 4);
ImprimirMatriz(m, 5, 4);
LiberarMatriz(m, 5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment