Search code examples
carrayspointersstructrealloc

Realloc array of pointers to an Struct in C


I have an struct like that:

struct _Total {
    Socio *socio[0];
    Libro *libro[0];
    int numsocios;
    int numlibros;
};

I have a practice in my university and I need to realloc "socio" and "libro" pointer each time I add data. For example, if a have only one "socio" the array need to be of size 1, if I add another "socio" I need to realloc it to size 2 and then add the pointer to the new struct (the counter is "numsocios"). Same for "libro".

I tried this function (in total.c file) but obviously I'm having type error:

STATUS total_ajustarsocio(Socio **socio, int tam) {

    Socio *temp = NULL;

    if (!socio) {
        return ERROR;
    }

    temp = (Socio *) realloc (*socio, tam * sizeof(Socio));

    if (!temp) {
        printf("Error reallocating Socio");
        return ERROR;
    }

    *socio = temp;

    return OK;
}

So, how can I solve mi problem?

P.S. This is the Socio struct (in socio.c - it has function to malloc and free in this file, too).

struct _Socio {
    char nombre[MAXCAR];
    char apellido[MAXCAR];
    int dni;
    char direccion[MAXCAR];
    int tlf;
    int numprestamos;
};

Thanks!


Solution

  • Your struct _Total is wrong. It should be:

    struct _Total {
        Socio *socio;
        Libro *libro;
        int numsocios;
        int numlibros;
    };
    

    Your total_ajustarsocio function might be called something like this:

    total.numsocios++;
    err = total_ajustarsocio(&total.socio, total.numsocios);