Re: Question c

Top Page

Reply to this message
Author: Edgar Bonet
Date:  
To: guilde
Subject: Re: Question c
Le dimanche 22 juin, Edgar Bonet a écrit :
>     #define ALLOC_STEP 1<<20    /* 2^10 doubles = 8 MiB */

>
>     typedef struct {
>         double *d;      /* data */
>         int n;          /* length */
>         int allocated;
>     } double_array;

>
>     static double_array new_array = { NULL, 0, 0 };

>
>     /* Returns 0 in success, -1 on failure. */
>     int array_push(double_array *a, double x)
>     {
>         if (a->n >= a->allocated) {
>             double *old_d = a->d;
>             a->allocated += ALLOC_STEP;
>             a->d = realloc(old_d, a->allocated * sizeof(double));
>             if (!a->d) {
>                 perror("realloc()");
>                 a->d = old_d;
>                 a->allocated -= ALLOC_STEP;
>                 return -1;
>             }
>         }
>         a->d[a->n++] = x;
>         return 0;
>     }


J'oubliais de préciser que je me sers ici du fait que

    realloc(NULL, sz);


est équivlent à

    malloc(sz);


Edgar.