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 <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
char * key;
char * value;
} stringPair;
int main(int argc, char * argv[]) /* pas de const dans le prototype de main */
{
char* list1;
char *key1;
stringPair * pPair1;
/*********************
key1="";
key1="test";
list1="";
list1="bonjour";
**********************/
/* allocation de l'espace memoire pour key1 et list1 */
list1 = key1 = pPair1 = NULL; /* initialisation a NULL pour la liberation en cas d'erreur */
key1 = malloc (200); /* taille a definir */
list1 = malloc (200); /* taille a definir */
pPair1=malloc(sizeof(stringPair));
/* verification */
if (key1 == NULL || list1 == NULL || pPair1 == NULL)
{
fprintf (stderr, "Erreur d'allocation memoire\n");
free (key1), key1 = NULL;
free (list1), list1 = NULL;
free (pPair1), pPair1 = NULL;
return EXIT_FAILURE;
}
/* la memoire est allouee. On peut ecrire dedans */
sprintf (key1, "test");
sprintf (list1, "bonjour");
/* on alloue le contenu de la structure */
pPair1->key = pPair1->value = NULL;
pPair1->key = malloc (300);
ppair1->value = malloc (300);
if (pPair1->key == NULL || pPair1->value == NULL)
{
fprintf (stderr, "Erreur d'allocation memoire\n");
free (key1), key1 = NULL;
free (list1), list1 = NULL;
free (pPair1->key), pPair1->key = NULL;
free (pPair1->value), pPair1->value = NULL;
free (pPair1), pPair1 = NULL;
return EXIT_FAILURE;
}
/* on peut copier les donnees. Utiliser strncpy serait mieux */
strcpy (pPair1->key, key1);
strcpy (pPair1->value,list1);
/* affichage */
fprintf(stdout, "%s and %s\n",pPair1->key, pPair1->value);
/* liberation memoire */
free (key1), key1 = NULL;
free (list1), list1 = NULL;
free (pPair1->key), pPair1->key = NULL;
free (pPair1->value), pPair1->value = NULL;
free (pPair1), pPair1 = NULL;
/* fin */
return EXIT_SUCCESS;
} |
Partager