Home > Back-end >  Number of Elements in a Struct in C
Number of Elements in a Struct in C

Time:02-28

I am new to C and I would like to know the size of an array of structs. I tried to use sizeof but it didn't work.

typedef struct Voitures{
    char categorie[20];
    char marque[15];
    char model[15];
    char boite[12];
    unsigned short int prix;
    unsigned short int qtt;
} Voiture;

Voiture liste_voitures[];

int main(){

    //elements added to liste_voitures[]

    prinft("%d", sizeof(liste_voitures)/sizeof(liste_voitures[0]);

    return 0;
}

How should I proceed?

CodePudding user response:

aha your edit makes it clearer now

If list_voitures is supposed to be a dynamically size array then you cannot find it out this way

The sizeof(lv)/sizeof(lv[0]) only works for fixed size array. In your case you created a zero size array so got the answer 0. If you do instead

 Voiture liste_voitures[10];

you will get 10.

But you want a dynamic array I think. You will have to keep track of the size yourself

Plus have

Voiture *liste_voitures;

which is a pointer to a voiture

  • Related