C为结构中的成员分配枚举值?

时间:2021-10-11 21:46:34

I have 2 enumerations, color with 2 colors, and car type with 13 car types. I have a car structure, with 2 respective members. How can I assign an enumerated value through a loop if my structure is in an array?

我有2个枚举,2种颜色的颜色和13种车型的车型。我有一个汽车结构,有2个相应的成员。如果我的结构在数组中,如何通过循环分配枚举值?

enum carType {A, B, C, D, E, F, G, H, I, J, K, L, M};
enum color {BLACK, WHITE};

typedef enum carType CarType;
typedef enum color Color;

struct car {                                 
CarType myCarType;
Color myColor;
};                  

typedef struct car Car;

void createGarage(Car *garage)
{ 



}

main()
{ 
Car garage[26];
createGarage(garage);
}

How can I loop through my array of garage, and ensure that each car type has both black and white colors?

如何在我的车库阵列中循环,并确保每种车型都有黑色和白色两种颜色?

I know I have 26 spaces in my garage array so I know I could use a for loop, but how would I exactly do the assignment?

我知道我的车库阵列中有26个空格,所以我知道我可以使用for循环,但是我如何完成任务呢?

1 个解决方案

#1


5  

You should add an extra element to each enum to hold the size, so you can loop over all the values.

您应该为每个枚举添加一个额外的元素来保存大小,这样您就可以循环遍历所有值。

enum carType {A, B, C, D, E, F, G, H, I, J, K, L, M, carType_size};
enum color {BLACK, WHITE, color_size};

void createGarage(Car *garage)
{ 
    for (int t = 0; t < carType_size; t++) {
        for (int c = 0; c < color_size; c++) {
            garage->carType = t;
            garage->color = c;
            garage++;
        }
    }   
}

This depends on the fact that enums default to assigning values sequentially from 0. This won't work if you have an enum where you override this with specific values, but that's an uncommon style.

这取决于枚举默认从0开始按顺序分配值的事实。如果你有一个枚举,你用特定值覆盖它,这将不起作用,但这是一种不常见的风格。

#1


5  

You should add an extra element to each enum to hold the size, so you can loop over all the values.

您应该为每个枚举添加一个额外的元素来保存大小,这样您就可以循环遍历所有值。

enum carType {A, B, C, D, E, F, G, H, I, J, K, L, M, carType_size};
enum color {BLACK, WHITE, color_size};

void createGarage(Car *garage)
{ 
    for (int t = 0; t < carType_size; t++) {
        for (int c = 0; c < color_size; c++) {
            garage->carType = t;
            garage->color = c;
            garage++;
        }
    }   
}

This depends on the fact that enums default to assigning values sequentially from 0. This won't work if you have an enum where you override this with specific values, but that's an uncommon style.

这取决于枚举默认从0开始按顺序分配值的事实。如果你有一个枚举,你用特定值覆盖它,这将不起作用,但这是一种不常见的风格。