简体   繁体   中英

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM