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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* -tc- macro qui determine le nombre d'elements d'un tableau alloue
statiquement */
#define NB_ELEMS(a) ( sizeof (a) / sizeof *(a) )
/**
* -tc- retourne un tableau de chaines de caracteres alloue dynamiquement.
* Le dernier element du tableau vaut NULL.
*/
char **test_tableau_chaines(void)
{
static char const *tab[] = {"un", "deux", "trois", "quatre", "cinq"};
char **p_return = NULL;
p_return = malloc((NB_ELEMS(tab) + 1) * sizeof *p_return);
/* -tc- TOUJOURS verifier la valeur retournee par malloc() */
if (p_return != NULL)
{
size_t i;
int err = 0;
for (i = 0; i < NB_ELEMS(tab) && err == 0; ++i)
{
/* -tc- on alloue la memoire et on copie chaque chaine
N.B. Cette operation peut etre realisee beaucoup plus
simple avec strdup() qui n'est pas standard, mais tres portable */
p_return[i] =malloc((strlen(tab[i]) + 1) * sizeof *p_return[i]);
if (p_return[i] != NULL)
{
strcpy(p_return[i], tab[i]);
}
else
{
err = 1;
}
}
/* -tc- en cas d'erreur, on fait le menage */
if (err != 0)
{
while (i > 0)
{
i--;
/* -tc- on libere la memoire de chaque element du tableau */
free(p_return[i]);
}
/* -tc- on libere la memoire du tableau */
free(p_return), p_return = NULL;
}
else
{
/* -tc- on affecte la valeur NULL au dernier element du tableau */
p_return[i] = NULL;
}
}
return p_return;
}
void test_tableau_chaines_free(char ***arr)
{
if (arr != NULL && *arr != NULL)
{
char **pp_self = *arr;
size_t i;
for (i = 0; pp_self[i] != NULL; ++i)
{
free(pp_self[i]);
}
free(pp_self);
*arr = NULL;
}
}
int main(void)
{
char **pp = NULL;
int ret = EXIT_SUCCESS;
pp = test_tableau_chaines();
if (pp != NULL)
{
size_t i = 0;
while (pp[i] != NULL)
{
printf ("%u: %s\n", (unsigned) i, pp[i]);
i++;
}
printf ("%u: %s\n", (unsigned) i, pp[i]);
test_tableau_chaines_free(&pp);
}
else
{
ret = EXIT_FAILURE;
}
return ret;
} |
Partager