所以,我为一个数组动态分配了内存,我想将它的所有值初始化为一个特定值(这是一个枚举的元素)。
这是我到目前为止所做的:
typedef enum{APPLE, BANANA, ORANGE} fruit;
typedef struct Smoothie Smoothie;
struct Smoothie {
fruit* tab;
};
这是我到目前为止定义的所有结构。现在,要创建“Smoothie”,我执行以下操作:
Smoothie init(size_t n) {
Smoothie* juice = malloc(sizeof(Smoothie));
if (juice == NULL) {
//error msg in case the allocation has failed.
}
juice->tab = calloc(n, sizeof(fruit));
if (juice->tab == NULL) {
//error msg in case the allocation has failed.
}
memset(juice->tab, APPLE, n*sizeof(fruit));
return *juice;
}
我的问题如下。根据我在 Internet 上能够阅读的内容,我知道 calloc()
已经将数组的所有值初始化为 0。在枚举中,所有元素都有一个数值(通过默认情况下,我的枚举具有以下值:Apple = 0 BANANA = 1 ORANGE = 2
)。那么,由于我想将数组的所有值初始化为 APPLE
,使用 memset()
是否非常有用?
换句话说,如果我不使用 memset()
会怎样?我如何确定编译器会理解我的数组中的值是 fruit
变量而不仅仅是整数?
PS:我知道我可以使用循环来初始化我的数组,但这样做的全部意义在于实际上避免使用循环。
最佳答案
So, since I want to initialize all the values of my array to
APPLE
, is it very useful to usememset()
?
没有。 memset()
用 byte 值填充一个区域。 enum
的大小可以变化,但通常是 int
,大于一个字节。你会用一些未定义的东西填满你的内存。 (当然,值为 0
的枚举成员除外)
How can I be sure that the compiler will understand that the values in my array are
fruit
variables and not just integers?
您已经通过将其声明为 fruit
类型来做到这一点。但这并没有太大帮助,因为 C 中整数和枚举值之间的转换是隐式的。
总而言之,如果您需要将内存初始化为0
以外的枚举值,则需要编写一个循环。如果你确实想要 0
对应的值,calloc()
就可以了,没关系因为 0
仍然是 0
:)
关于c - 在 C 中使用特定值初始化动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49634681/