57 lines
1.1 KiB
C
57 lines
1.1 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
int **allocate_matrix(int rows, int cols)
|
|
{
|
|
int **matrix = malloc(rows * sizeof(int *));//creation du tableau X hauteur
|
|
if (!matrix)
|
|
return NULL;
|
|
for (int i = 0; i < rows; i++)
|
|
{
|
|
matrix[i] = malloc(cols * sizeof(int));//creation des colonnes
|
|
//on free les cols si la matrice n'existe pas
|
|
if (!matrix[i])
|
|
{
|
|
for (int j = 0; j < i; j++)
|
|
free(matrix[j]);
|
|
free(matrix);
|
|
return NULL;
|
|
}
|
|
}
|
|
return matrix;
|
|
}
|
|
|
|
void free_matrix(int **matrix, int rows)
|
|
{
|
|
if (!matrix)
|
|
return;
|
|
//ajout
|
|
for (int j = 0; j < rows; j ++)
|
|
free(matrix[j]);
|
|
free(matrix);
|
|
return;
|
|
}
|
|
|
|
int main(void)
|
|
{
|
|
int rows = 5;
|
|
int cols = 5;
|
|
int **matrix = allocate_matrix(rows, cols);
|
|
if (!matrix)
|
|
{
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
for (int i = 0; i < rows; i++)
|
|
{
|
|
for (int j = 0; j < cols; j++)
|
|
{
|
|
matrix[i][j] = i * cols + j;
|
|
}
|
|
}
|
|
|
|
free_matrix(matrix, rows);
|
|
//free(matrix);
|
|
return EXIT_SUCCESS;
|
|
}
|