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 118 119 120
| typedef struct {
int *tab;
size_t width, height;
} s_table;
char table_init (s_table *table, int width, int height) {
if (!table) {
fprintf (stderr, "Impossible to init table !\n");
fprintf (stderr, "table must be valid in %s();\n", __func__);
return 0;
}
if (width<0 || height<0) {
fprintf (stderr, "Impossible to init table !\n");
fprintf (stderr, "size of table must be >=0 in %s();\n", __func__);
return 0;
}
table->tab = calloc (width*height, sizeof(int));
if (!table->tab) {
fprintf (stderr, "An error is occured to initialize table ! \n");
return 0;
}
table->width = width;
table->height = height;
return 1;
}
void table_free (s_table *table) {
if (!table)
return;
free (table->tab);
}
char table_set_value (s_table *table, int x, int y, int value)
{
if (!table) {
fprintf (stderr, "table must be valid in %s();\n", __func__);
return 0;
}
if (x<0 || y<0) {
fprintf (stderr, "coordinates must be >=0 in %s();\n", __func__);
return 0;
}
if (x>table->width-1 || y>table->height-1) {
fprintf (stderr, "coordinates are too big in %s();\n", __func__);
return 0;
}
table->tab[x + table->width*y] = value;
return 1;
}
int table_get_value (s_table *table, int x, int y, char *error)
{
*error = 0;
if (!table) {
fprintf (stderr, "table must be valid in %s\n", __func__);
return -1;
}
if (x<0 || y<0) {
fprintf (stderr, "coordinates must be >=0 in %s\n", __func__);
return -1;
}
if (x>table->width-1 || y>table->height-1) {
fprintf (stderr, "coordinates are too big in %s\n", __func__);
return -1;
}
*error = 1;
return table->tab[x + table->width*y];
}
int
main (int argc, char **argv)
{
/* Déclaration d'une taille arbitraire d'un tableau à deux dimensions */
int a=10, b=20;
/* Initialisation du tableau */
s_table table;
if (!table_init (&table, a, b)) {
exit(EXIT_FAILURE);
}
/* Placement d'une valeur aux coordonnées (9, 8) */
if (!table_set_value (&table, 9, 8, -12)) {
/* Libération mémoire */
table_free (&table);
exit(EXIT_FAILURE);
}
/* Récupération d'une donnée aux coordonnées (9, 8) */
char error; /* Pour vérifier si une erreur est survenue */
int value; /* Valeur retournée */
value = table_get_value (&table, 9, 8, &error);
if (!error) {
/* Libération mémoire */
table_free (&table);
exit(EXIT_FAILURE);
}
else
printf ("value is : %d\n", value);
/* Libération mémoire */
table_free (&table);
return EXIT_SUCCESS;
} |
Partager