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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256
/* définition d'un type struct etudiant */
struct etudiant {
char nom[MAX];
char prenom[MAX];
float moyenne;
};
void set_etudiant(struct etudiant * e, char * nom, char * prenom, float moyenne) {
strcpy(e->nom, nom);
strcpy(e->prenom, prenom);
e->moyenne = moyenne;
}
int main(void) {
/* déclaration d'une variable de type pointeur sur struct etudiant */
struct etudiant * etudiants;
/* initialisation du pointeur avec malloc permettant de stocker
* 35 étudiants dans la zone mémoire réservée */
etudiants = malloc(35 * sizeof(struct etudiant));
/* initialisation du premier étudiant, l'opérateur crochets
* opère le déréférencement et on accède au membre avec
* l'opérateur . simplement */
strcpy(etudiants[0].nom, "Chaplin");
strcpy(etudiants[0].prenom, "Charlie");
etudiants[0].moyenne = 20.0;
/* initialisation au moyen d'une fonction dédiée */
set_etudiant(&etudiants[1], "Harold", "Lloyd", 20.0);
set_etudiant(&etudiants[2], "Buster", "Keaton", 20.0);
/* afficher les étudiants */
// TODO
/* lorsqu'on n'a plus besoin de l'espace mémoire pointé par
* etudiants, on le libère avec free */
free(etudiants);
return 0;
} |
Partager