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
|
#include <string.h>
struct Adresse {
int numero;
char rue[128];
char codePostal[8];
char ville[50];
char pays[50];
};
typedef struct Contact Contact;
struct Contact{
char nom[50];
char prenom[50];
int age;
Adresse adresse;
};
typedef struct // Déclaration plus courte.
{
int taille_reserve ;
int taille_reelle ;
Contact* tous ;
} Carnet ;
void init ( Carnet* carnet )
{
carnet->taille_reserve = 0 ;
carnet->taille_reelle = 0 ;
carnet->tous = NULL ;
}
void extend_memory ( Carnet* pCarnet , int new_size )
{
if(pCarnet->tous == NULL){
pCarnet->tous = (Contact*) malloc(new_size * sizeof(Contact));
}else{
pCarnet->tous = (Contact*) realloc(pCarnet->tous, ((new_size + pCarnet->taille_reserve) * sizeof(Contact)));
}
if(pCarnet->tous == NULL){
printf("Erreur allocation !");
exit(EXIT_FAILURE);
}
pCarnet->taille_reserve += new_size ;
}
void ajouter_contact ( Carnet* pCarnet , const char* nom )
{
// Verification qu'il reste assez de place, sinon soit code d'erreur ou reallocation tacite. Non fait ici..
strncpy( pCarnet->tous[pCarnet->taille_reelle].nom , nom, 50) ;
++(pCarnet->taille_reelle) ;
}
int main()
{
Carnet carnet ;
init( &carnet );
extend_memory( &carnet, 1 );
ajouter_contact( &carnet, "Gertrude" );
extend_memory( &carnet, 10 ) ;
ajouter_contact( &carnet, "Jean" ) ;
printf("%s\n",carnet.tous[0].nom );
printf("%s\n", carnet.tous[1].nom );
return 0;
} |
Partager