Created
April 7, 2019 21:37
-
-
Save santiagosilas/3ea623a5e6b553a066a51f9f02952bca to your computer and use it in GitHub Desktop.
ANSI C - Alocação Dinâmica de Matrizes - Exemplo com Funções
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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