1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| #include <stdio.h>
#include <stdlib.h>
/* -tc- Cree une matrice. Cette fonction retourne la valeur NULL en cas d'echec
de l'alloocation de memoire */
double **matrice_creer(size_t nlignes, size_t ncols)
{
double **matrice = NULL;
if (nlignes > 0 && ncols > 0)
{
/* -tc- multiplier le nombre de lignes par la taille d'un element de
type (double **) */
matrice = malloc((nlignes + 1) * sizeof *matrice);
/* -tc- TOUJOURS verifier que l'allocation a reussi avant d'aller plus
loin */
if (matrice != NULL)
{
size_t i, j;
int err = 0;
for (i = 0; err == 0 && i < nlignes; i++)
{
matrice[i] = malloc(ncols * sizeof *matrice[i]);
if (matrice[i] != NULL)
{
/* -tc- Allocation OK. On initialise la matrice */
for (j = 0; j < ncols; j++)
{
matrice[i][j] = 0.0;
}
}
else
{
/* -tc- Erreur d'allocation */
err = 1;
/* -tc- ...on fait le menage */
while (i > 0)
{
i--;
free(matrice[i]);
}
free(matrice), matrice = NULL;
}
}
if (err == 0 && i == nlignes)
{
/* -tc- sentinelle en vue de la liberation de memoire */
matrice[i] = NULL;
}
}
}
return matrice;
}
/* -tc- Destruction de la matrice */
void matrice_detruire(double **self)
{
if (self != NULL)
{
size_t i = 0;
while (self[i] != NULL)
{
free(self[i]);
i++;
}
free(self);
}
}
int main(void)
{
double **X = NULL;
size_t const nombre_de_lignes = 3;
size_t const nombre_de_colonnes = 4;
int ret = 0;
X = matrice_creer(nombre_de_lignes, nombre_de_colonnes);
/* -tc- Il faut toujours verifier que l'allocation se passe bien */
if (X != NULL)
{
double **X2 = matrice_creer(nombre_de_lignes, nombre_de_colonnes);
if (X2 != NULL)
{
/* -tc- Copie de X dans X2 */
size_t i, j;
for (i = 0; i < nombre_de_lignes; i++)
{
for (j = 0; j < nombre_de_colonnes; j++)
{
X2[i][j] = X[i][j];
}
}
matrice_detruire(X2), X2 = NULL;
}
else
{
fprintf(stderr, "Erreur: allocation impossible");
ret = EXIT_FAILURE;
}
matrice_detruire(X), X = NULL;
}
else
{
fprintf(stderr, "Erreur: allocation impossible");
ret = EXIT_FAILURE;
}
return ret;
} |