Expand|Select|Wrap|Line Numbers
- typedef struct array
- {
- double *x, *y;
- size_t nelem, size;
- } array_t;
- #define INIT_A_SIZE 1
- int init_a(array_t *a)
- {
- if (a) {
- a->x = (double *)malloc(INIT_A_SIZE*sizeof(double));
- a->y = (double *)malloc(INIT_A_SIZE*sizeof(double));
- if (!a->x || !a->y) {
- /* technically I should free x here is y fails
- but that's not the issue */
- return -1;
- }
- a->nelem = 0;
- a->size = INIT_A_SIZE;
- }
- return 0;
- }
- int add_a(array_t *a, double x, double y)
- {
- if (a->nelem == a->size) {
- size_t newsize;
- double *newx, *newy;
- newsize = 2*a->size;
- newx = realloc(a->x, newsize);
- if (!newx) {
- return -2;
- }
- newy = realloc(a->y, newsize);
- if (!newy) {
- a->x = realloc(a->x, a->size);
- return -3;
- }
- a->size = newsize;
- a->x = newx;
- a->y = newy;
- }
- a->x[a->nelem] = x;
- a->y[a->nelem] = y;
- a->nelem++;
- return 0;
- }
This has come up before, and I went through the threads, but (as far as I can tell) my situation is different than any previous posters, because unlike their code, this code:
1. assigns reallocated pointer to original (a->x = newx)
2. does not free anything
3. checks if newx or newy are NULL