JuMoGar
JuMoGar

Reputation: 1760

C - error: array type has incomplete element type in a extern struct declaration

I have next code:

// FILE: HEADERS.h
extern struct viaje viajes[];
extern struct cliente clientes[];

// FILE: STRUCTS.c
struct viaje {
    char identificador[30+1];
    char ciudadDestino[30+1];
    char hotel[30+1];
    int numeroNoches;
    char tipoTransporte[30+1];
    float precioAlojamiento;
    float precioDesplazamiento;
};

struct cliente {
    char dni[30+1];
    char nombre[30+1];
    char apellidos[30+1];
    char direccion[30+1];
    int totalViajes;
    struct viaje viajes[50];
} clientes[20];

When I try to complile code I get next error: error: array type has incomplete element type in a extern struct declaration and I do not know why could it be. I have tried also include header after Structs definition and I do not get any error, but it is wrong, the correct way is Define -> Declare, not Declare -> Define.

Why could it be?. Thank you.

Upvotes: 1

Views: 2644

Answers (1)

dbush
dbush

Reputation: 225007

If you define or declare an instance of a struct, that struct needs to be defined first. Otherwise, the compiler can't figure out the size of the structure or what its members are.

You need to put the struct definitions first in your header file before the extern declarations:

struct viaje {
    char identificador[30+1];
    char ciudadDestino[30+1];
    char hotel[30+1];
    int numeroNoches;
    char tipoTransporte[30+1];
    float precioAlojamiento;
    float precioDesplazamiento;
};

struct cliente {
    char dni[30+1];
    char nombre[30+1];
    char apellidos[30+1];
    char direccion[30+1];
    int totalViajes;
    struct viaje viajes[50];
};   // note that there are no instances defined here

extern struct viaje viajes[];
extern struct cliente clientes[];

Then your .c file would contain the instances:

// Changed size viajes from 20 to 50
struct viaje viajes[50];
struct cliente clientes[20];

Upvotes: 4

Related Questions