mercredi 21 juillet 2021

How can I cycle through each member of a structure variable?

This code is just a simplified version of what I'm looking for. Generally I'd like to know how to access any type of variable, so maybe I could type horse[6] to access an int, and horse[7] to access a char as well.

#include<stdio.h>

struct horse_s{
    int age;
    int height;
    int width;
    int weight;
}horse;

struct horse_s horse_default = {1, 2, 3, 4};

int main(){
    int i;
    int a = sizeof(struct horse); //I want this to return the amount of members in the struct
    for(i = 0; i<a; i++){
        horse_1[i] = horse_default[i] + 2; //I want this to access the i-th member of the struct variable
    }

    printf("Horse age: %d\n", horse.age);
    printf("Horse height: %d\n", horse.height);
    printf("Horse width: %d\n", horse.width);
    printf("Horse weight: %d\n", horse.weight);

    return 0;
}




Aucun commentaire:

Enregistrer un commentaire