Programmation C
struct, typedef & enum - Correction des exercices
Cours Exercices Correction des exercices

Exercice 1 Exercice 2 Exercice 3 Exercice 4
Exercice 5 Exercice 6 Exercice 7 Exercice 8

Exercice 1

#include <stdio.h>

struct personnage {
  char nom[65];
  int combat;
  int vie;
  int magie;
};

int main(void) {
  struct personnage gandalf;
  printf("%zu octets (type) %zu octets (variable)\n",
         sizeof(struct personnage),
         sizeof(gandalf));
  return 0;
}

07-Exercice1.c - 07-Exercice1.exe
***
  • RAS

Exercice 2

#include <stdio.h>
#include <math.h>

#define PI 3.141592653589793

struct angle {
  int degres;
  int minutes;
  int secondes;
  char dir;
};

struct positionGPS {
  struct angle latitude;
  struct angle longitude;
};

double convertirVersDoubleEnRadian(struct angle a) {
  double ang = (a.degres + a.minutes / 60.0 + a.secondes / 3600.0)*PI/180.0;
  if ((a.dir == 'O') || (a.dir == 'S')) {
    ang = -ang;
  }
  return ang;
}

double calculerDistanceOrthodromique(struct positionGPS p1, struct positionGPS p2) {
  double lat1 = convertirVersDoubleEnRadian(p1.latitude);
  double lat2 = convertirVersDoubleEnRadian(p2.latitude);
  double lon1 = convertirVersDoubleEnRadian(p1.longitude);
  double lon2 = convertirVersDoubleEnRadian(p2.longitude);
  double dist = 6378.0 * acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1));
  return dist;
}

void afficherAngle(struct angle a) {
  printf("[%03d:%02d:%02d:%c]", a.degres, a.minutes, a.secondes, a.dir);
}

void afficherPositionGPS(struct positionGPS p) {
  printf("[");
  afficherAngle(p.latitude);
  printf("-");
  afficherAngle(p.longitude);
  printf("]");
}

int main(void) {
  struct positionGPS p1 = { {47,14,16,'N'},{6,1,27,'E'} };     // Besancon
  struct positionGPS p2 = { {17,32,6,'S'},{149,34,11,'O'} };   // Papeete
  printf("La distance entre\n");
  afficherPositionGPS(p1);
  printf("\net\n");
  afficherPositionGPS(p2);
  printf("\nest %lf km.\n", calculerDistanceOrthodromique(p1, p2));
  return 0;
}

07-Exercice2.c - 07-Exercice2.exe
***
  • RAS

Exercice 3

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct collection {
  int n;
  int* t;
};

struct collection creerCollectionVide(void) {
  struct collection c;
  c.n = 0;
  c.t = NULL;
  return c;
};

void afficherCollection(struct collection c) {
  printf("%d valeur(s) :", c.n);
  for (int i = 0; i < c.n; i++) {
    printf(" %d", c.t[i]);
  }
  printf("\n");
}

void viderCollection(struct collection* c) {
  if (c->t != NULL) {
    free(c->t);
    c->t = NULL;
  }
  c->n = 0;
}

bool creerCollection(struct collection* c, int n, int max) {
  viderCollection(c);
  c->n = n;
  c->t = (int*) calloc(n, sizeof(int));
  if (c->t == NULL) {
    c->n = 0;
    return false;
  }
  else {
    for (int i = 0; i < n; i++) {
      c->t[i] = 1 + rand() % max;
    }
    return true;
  }
}

bool etreVide(struct collection* c) {
  return c->n == 0;
}

bool exister(int val, int* t, int indi, int indf) {
  bool res = false;
  int i = indi;
  while ((i <= indf) && ((res = (t[i] == val)) == false)) {
    i++;
  }
  return res;
}

bool etreEnsemble(struct collection* c) {
  if (c->n <= 1) {
    return true;
  }
  bool res = true;
  int i = 0;
  do {
    if (exister(c->t[i], c->t, i + 1, c->n - 1)) {
      res = false;
    }
    i++;
  } while (i < c->n - 1);
  return res;
}

bool etreInclus(int val, struct collection c) {
  return exister(val, c.t, 0, c.n - 1);
}

int chercherIndice(int val, struct collection c) {
  bool trouve = false;
  int i = 0;
  while ((i <= c.n - 1) && ((trouve = (c.t[i] == val)) == false)) {
    i++;
  }
  if (trouve == false) {
    return -1;
  }
  return i;
}

bool ajouterEntier(int val, struct collection* c) {
  if (etreInclus(val, *c) == true) {
    return false;
  }
  int* nt = (int*) realloc(c->t, (c->n + 1) * sizeof(int));
  if (nt == NULL) {
    return false;
  }
  nt[c->n] = val;
  c->n++;
  c->t = nt;
  return true;
}

bool retirerEntier(int val, struct collection* c) {
  int ind = chercherIndice(val, *c);
  if (ind == -1) {
    return false;
  }
  if (c->n == 1) {
    free(c->t);
    c->t = NULL;
    c->n = 0;
    return true;
  }
  if (ind != c->n - 1) {
    int aux = c->t[ind];
    c->t[ind] = c->t[c->n - 1];
    c->t[c->n - 1] = aux;
  }
  int* nt = (int*) realloc(c->t, (c->n - 1) * sizeof(int));
  if (nt == NULL) {
    return false;
  }
  c->n--;
  c->t = nt;
  return true;
}

bool creerCopie(struct collection e, struct collection* resultat) {
  viderCollection(resultat);
  int i = 0;
  bool onGo = true;
  while ((i < e.n) && (onGo == true)) {
    if (ajouterEntier(e.t[i], resultat) == false) {
      onGo = false;
      viderCollection(resultat);
    }
    i++;
  }
  return onGo;
}

bool calculerSoustraction(struct collection e1, struct collection e2, struct collection* resultat) {
  viderCollection(resultat);
  int i = 0;
  bool onGo = true;
  while ((i < e1.n) && (onGo == true)) {
    if (etreInclus(e1.t[i], e2) == false) {
      if (ajouterEntier(e1.t[i], resultat) == false) {
        onGo = false;
        viderCollection(resultat);
      }
    }
    i++;
  }
  return onGo;
}

bool calculerUnion(struct collection e1, struct collection e2, struct collection* resultat) {
  viderCollection(resultat);
  if (creerCopie(e1,resultat) == false) {
    return false;
  }
  struct collection s = creerCollectionVide();
  if (calculerSoustraction(e2, e1, &s) == false) {
    viderCollection(resultat);
    return false;
  }
  int i = 0;
  bool onGo = true;
  while ((i < s.n) && (onGo == true)) {
      if (ajouterEntier(s.t[i], resultat) == false) {
        onGo = false;
        viderCollection(resultat);
        viderCollection(&s);
      }
    i++;
  }
  viderCollection(&s);
  return onGo;
}

bool calculerIntersection(struct collection e1, struct collection e2, struct collection* resultat) {
  viderCollection(resultat);
  int i = 0;
  bool onGo = true;
  while ((i < e1.n) && (onGo == true)) {
    if (etreInclus(e1.t[i], e2) == true) {
      if (ajouterEntier(e1.t[i], resultat) == false) {
        onGo = false;
        viderCollection(resultat);
      }
    }
    i++;
  }
  return onGo;
}

void testerCreationVide(void) {
  struct collection col = creerCollectionVide();
  printf("Collection vide cree\n");
  viderCollection(&col);
  printf("Collection vide videe (!)\n");
  printf("\n");
}

void testerCreationNonVide(void) {
  struct collection col;
  const int MAX = 100;
  if (creerCollection(&col, 20, MAX) == true) {
    printf("Collection cree\n");
    afficherCollection(col);
    for (int i = 1; i <= MAX; i++) {
      if (etreInclus(i, col) == true) {
        printf("%3d", i);
      }
    }
    printf("\n");
    if (etreEnsemble(&col) == true) {
      printf("C'est un ensemble\n");
    }
    else {
      printf("Ce n'est pas un ensemble\n");
    }
    viderCollection(&col);
    printf("Collection videe\n");
  }
  printf("\n");
}

void testerAjoutsEtRetraits(void) {
  struct collection col = creerCollectionVide();
  afficherCollection(col);
  int v = 11;
  if (ajouterEntier(v, &col) == true) {
    printf("Ajout de %d reussi\n", v);
  }
  else {
    printf("Ajout de %d ratee\n", v);
  }
  v = -6;
  if (ajouterEntier(v, &col) == true) {
    printf("Ajout de %d reussi\n", v);
  }
  else {
    printf("Ajout de %d ratee\n", v);
  }
  afficherCollection(col);
  v = 2;
  if (ajouterEntier(v, &col) == true) {
    printf("Ajout de %d reussi\n", v);
  }
  else {
    printf("Ajout de %d ratee\n", v);
  }
  afficherCollection(col);
  v = 11;
  if (ajouterEntier(v, &col) == true) {
    printf("Ajout de %d reussi\n", v);
  }
  else {
    printf("Ajout de %d ratee\n", v);
  }
  afficherCollection(col);
  v = 2;
  if (retirerEntier(v, &col) == true) {
    printf("Retrait de %d reussi\n", v);
  }
  else {
    printf("Retrait de %d rate\n", v);
  }
  afficherCollection(col);
  v = -6;
  if (retirerEntier(v, &col) == true) {
    printf("Retrait de %d reussi\n", v);
  }
  else {
    printf("Retrait de %d rate\n", v);
  }
  afficherCollection(col);
  v = 11;
  if (retirerEntier(v, &col) == true) {
    printf("Retrait de %d reussi\n", v);
  }
  else {
    printf("Retrait de %d rate\n", v);
  }
  afficherCollection(col);
  viderCollection(&col);
  printf("Collection videe\n");
  printf("\n");
}

void testerSoustraction(void) {
  struct collection e1 = creerCollectionVide();
  struct collection e2 = creerCollectionVide();
  struct collection res = creerCollectionVide();
  ajouterEntier(3, &e1);
  ajouterEntier(4, &e1);
  ajouterEntier(8, &e1);
  ajouterEntier(-2, &e1);
  ajouterEntier(0, &e1);
  ajouterEntier(-2, &e2);
  ajouterEntier(8, &e2);
  ajouterEntier(9, &e2);
  ajouterEntier(-3, &e2);
  printf("e1      : ");
  afficherCollection(e1);
  printf("e2      : ");
  afficherCollection(e2);
  calculerSoustraction(e1, e2, &res);
  printf("e1 - e2 : ");
  afficherCollection(res);
  calculerSoustraction(e2, e1, &res);
  printf("e2 - e1 : ");
  afficherCollection(res);
  viderCollection(&e1);
  viderCollection(&e2);
  viderCollection(&res);
  printf("\n");
}

void testerCopie(void) {
  struct collection e = creerCollectionVide();
  struct collection res = creerCollectionVide();
  ajouterEntier(3, &e);
  ajouterEntier(4, &e);
  ajouterEntier(8, &e);
  ajouterEntier(-2, &e);
  ajouterEntier(0, &e);
  ajouterEntier(9, &e);
  ajouterEntier(-3, &e);
  printf("e          : ");
  afficherCollection(e);
  creerCopie(e, &res);
  printf("copie de e : ");
  afficherCollection(res);
  viderCollection(&e);
  viderCollection(&res);
  printf("\n");
}

void testerUnion(void) {
  struct collection e1 = creerCollectionVide();
  struct collection e2 = creerCollectionVide();
  struct collection res = creerCollectionVide();
  ajouterEntier(3, &e1);
  ajouterEntier(4, &e1);
  ajouterEntier(8, &e1);
  ajouterEntier(-2, &e1);
  ajouterEntier(0, &e1);
  ajouterEntier(-2, &e2);
  ajouterEntier(8, &e2);
  ajouterEntier(9, &e2);
  ajouterEntier(-3, &e2);
  printf("e1           : ");
  afficherCollection(e1);
  printf("e2           : ");
  afficherCollection(e2);
  calculerUnion(e1, e2, &res);
  printf("union(e1,e2) : ");
  afficherCollection(res);
  calculerUnion(e2, e1, &res);
  printf("union(e2,e1) : ");
  afficherCollection(res);
  viderCollection(&e1);
  viderCollection(&e2);
  viderCollection(&res);
  printf("\n");
}

void testerIntersection(void) {
  struct collection e1 = creerCollectionVide();
  struct collection e2 = creerCollectionVide();
  struct collection res = creerCollectionVide();
  ajouterEntier(3, &e1);
  ajouterEntier(4, &e1);
  ajouterEntier(8, &e1);
  ajouterEntier(-2, &e1);
  ajouterEntier(0, &e1);
  ajouterEntier(-2, &e2);
  ajouterEntier(8, &e2);
  ajouterEntier(9, &e2);
  ajouterEntier(-3, &e2);
  printf("e1                  : ");
  afficherCollection(e1);
  printf("e2                  : ");
  afficherCollection(e2);
  calculerIntersection(e1, e2, &res);
  printf("intersection(e1,e2) : ");
  afficherCollection(res);
  calculerIntersection(e2, e1, &res);
  printf("intersection(e2,e1) : ");
  afficherCollection(res);
  viderCollection(&e1);
  viderCollection(&e2);
  viderCollection(&res);
  printf("\n");
}

int main(void) {
  testerCreationVide();
  testerCreationNonVide();
  testerAjoutsEtRetraits();
  testerCopie();
  testerSoustraction();
  testerUnion();
  testerIntersection();
  return 0;
}

07-Exercice3.c - 07-Exercice3.exe
***
  • RAS

Exercice 4

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct position {
  double x;
  double y;
  double z;
};

struct cube {
  double cote;
  struct position centre;
};

int myRand(void) {
  return rand() * (RAND_MAX + 1) + rand();
}

int randDansIntervalle(int bi, int bf) {
  return bi + myRand() % (bf - bi + 1);
}

struct cube* creerTableauCubes(int n) {
  return (struct cube*) calloc(n, sizeof(struct cube));
}

void initialiserTableauCubes(struct cube* tc, int n) {
  for (int i = 0; i < n; i++) {
    tc[i].centre.x = randDansIntervalle(-5000, 5000) / 100.0;
    tc[i].centre.y = randDansIntervalle(-5000, 5000) / 100.0;
    tc[i].centre.z = randDansIntervalle(-5000, 5000) / 100.0;
    tc[i].cote = randDansIntervalle(500, 1500) / 100.0;
  }
}

bool etreInclusePositionDansCube(struct position p, struct cube cb) {
  double cs2 = cb.cote / 2.0;
  return ((p.x >= cb.centre.x - cs2) && (p.x <= cb.centre.x + cs2) &&
          (p.y >= cb.centre.y - cs2) && (p.y <= cb.centre.y + cs2) &&
          (p.z >= cb.centre.z - cs2) && (p.z <= cb.centre.z + cs2));
}

void afficherIndicesCubes(struct cube* tc, int n, struct position p) {
  for (int i = 0; i < n; i++) {
    if (etreInclusePositionDansCube(p, tc[i]) == true) {
      printf("%5d\n", i);
    }
  }
}

void afficherCubes(struct cube* tc, int n) {
  for (int i = 0; i < n; i++) {
    printf("%5d : %7.2lf %7.2lf %7.2lf : %7.3lf\n",
           i,
           tc[i].centre.x,
           tc[i].centre.y,
           tc[i].centre.z,
           tc[i].cote);
  }
}

int main(void) {
  const int N = 1000;
  struct cube* tc = creerTableauCubes(N);
  if (tc == NULL) {
    printf("Tableau de cubes non cree\n");
    return 1;
  }
  printf("Tableau de %d cubes cree\n", N);
  initialiserTableauCubes(tc, N);
  printf("Tableau de %d cubes initialise\n", N);
  struct position p = { -30.0,30.0,-20.0 };
  //afficherCubes(tc, N);
  afficherIndicesCubes(tc, N, p);
  free(tc);
  tc = NULL;
  printf("Tableau libere\n");
  return 0;
}

07-Exercice4.c - 07-Exercice4.exe
***
  • RAS

Exercice 5

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct pile1 {
  unsigned sp;
  long long tll[1000000];
};

struct pile2 {
  unsigned sp;
  unsigned tMax;
  long long *tll;
};

struct enregistrement {
  long long info;
  struct enregistrement* inferieur;
};

struct pile {
  struct enregistrement* sp;
};

struct pile creerPileVide(void) {
  struct pile p = { NULL };
  return p;
}

void libererEnregistrement(struct enregistrement* e) {
  if (e != NULL) {
    libererEnregistrement(e->inferieur);
    free(e);
    e = NULL;
  }
}

void viderPile(struct pile *p) {
  libererEnregistrement(p->sp);
}

bool etreVide(struct pile p) {
  return p.sp == NULL;
}

bool empiler(struct pile* p, long long val) {
  struct enregistrement* e = (struct enregistrement*) calloc(1, sizeof(struct enregistrement));
  if (e == NULL) {
    return false;
  }
  e->info = val;
  e->inferieur = p->sp;
  p->sp = e;
  return true;
}

bool depiler(struct pile* p, long long* val) {
  if (p->sp == NULL) {
    return false;
  }
  *val = p->sp->info;
  struct enregistrement* inf = p->sp->inferieur;
  free(p->sp);
  p->sp = inf;
  return true;
}

int main(void) {

  struct pile p = creerPileVide();
  printf("Pile creee\n");
  for (int i = 0; i <= 100; i += 2) {
    empiler(&p, i);
  }
  while (!etreVide(p)) {
    long long v;
    depiler(&p, &v);
    printf("%lld\n", v);
  }
  viderPile(&p);
  printf("Pile videe\n");
  return 0;
}

07-Exercice5.c - 07-Exercice5.exe
***
  • RAS

Exercice 6

#include <stdio.h>

typedef float coefficient;

typedef struct {
  coefficient rouge;
  coefficient vert;
  coefficient bleu;
couleur;

const couleur NOIR = { 0.0F,0.0F,0.0F };
const couleur ROUGE = { 1.0F,0.0F,0.0F };
const couleur VERT = { 0.0F,1.0F,0.0F };
const couleur BLEU = { 0.0F,0.0F,1.0F };
const couleur CYAN = { 0.0F,1.0F,1.0F };
const couleur MAGENTA = { 1.0F,0.0F,1.0F };
const couleur JAUNE = { 1.0F,1.0F,0.0F };
const couleur BLANC = { 1.0F,1.0F,1.0F };

void afficherCouleur(couleur coul) {
  printf("[%5.3f,%5.3f,%5.3f]",coul.rouge,coul.vert,coul.bleu);
}

int main(void) {
  afficherCouleur(CYAN);
  printf("\n");
  afficherCouleur(JAUNE);
  printf("\n");
  return 0;
}

07-Exercice6.c - 07-Exercice6.exe
***
  • RAS

Exercice 7

#include <stdio.h>

enum {
  NO_ERROR = 0,
  INVALID_OPERATION = 10,
  INVALID_VALUE = 11,
  STACK_OVERFLOW = 12,
  STACK_UNDERFLOW = 13,
  OUT_OFF_MEMORY = 14
};

int main(void) {
  printf("%d\n%d\n",NO_ERROR, OUT_OFF_MEMORY);
  return 0;
}

07-Exercice7.c - 07-Exercice7.exe
***
  • RAS

Exercice 8

#include <stdio.h>
#include <stdbool.h>

typedef enum {
  UNAUTHORIZED = 0B000000,
  READ = 0B000001,
  WRITE = 0B000010,
  EXECUTE = 0B000100,
  DELETE = 0B001000,
  CHANGE_PERMISSION = 0B010000,
  CHANGE_OWNER = 0B100000
autorisationElementaire;

typedef int compositionAutorisations;

compositionAutorisations calculerCompositionAutorisations(autorisationElementaire r,
                                                          autorisationElementaire w,
                                                          autorisationElementaire x,
                                                          autorisationElementaire d,
                                                          autorisationElementaire p,
                                                          autorisationElementaire o) {
  compositionAutorisations cmp = r | w | x | d | p | o;
  return cmp;
}

bool testerAutorisation(compositionAutorisations ca, autorisationElementaire ae) {
  return (ca & ae) == ae;
}

int main(void) {
  printf("%d %d %d %d %d %d %d\n",UNAUTHORIZED,READ,WRITE,EXECUTE,DELETE,CHANGE_PERMISSION,CHANGE_OWNER);
  compositionAutorisations jeu = calculerCompositionAutorisations(READ,
                                                                  UNAUTHORIZED,
                                                                  EXECUTE,
                                                                  DELETE,
                                                                  UNAUTHORIZED,
                                                                  UNAUTHORIZED);
  printf("Valeur du jeu d'aurorisations : %d\n", jeu);
  printf("Lecture  : %d\n", testerAutorisation(jeu, READ));
  printf("Ecriture : %d\n", testerAutorisation(jeu, WRITE));
  return 0;
}

07-Exercice8.c - 07-Exercice8.exe
***
  • RAS