So, I have dynamically allocated memory for an array and I want initialize all its values to a specific value (which is an element of an enumeration).
Here's what I've done so far:
typedef enum{APPLE, BANANA, ORANGE} fruit;
typedef struct Smoothie Smoothie;
struct Smoothie {
fruit* tab;
};
This is all the structures I've defined so far. Now, to create the "Smoothie", I do the following:
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;
}
My question is the following. From what I've been able to read on the internet, I know that calloc()
already initializes all the values of the array at 0. In an enumeration, all the elements have a numerical value (by default, my enumeration has the following values: Apple = 0 BANANA = 1 ORANGE = 2
). So, since I want to initialize all the values of my array to APPLE
, is it very useful to use memset()
?
In other words, what happens if I do not use memset()
? How can I be sure that the compiler will understand that the values in my array are fruit
variables and not just integers?
PS: I know that I could use a loop ot initilize my array, but the whole point of this is to actually avoid using the loop.
So, since I want to initialize all the values of my array to
APPLE
, is it very useful to usememset()
?
No. memset()
fills an area with a byte value. The size of an enum
can vary, but it is normally an int
, which is larger than a byte. You will fill your memory with something undefined. (Except of course for the enum member with the value 0
)
How can I be sure that the compiler will understand that the values in my array are
fruit
variables and not just integers?
You already did that by declaring it of type fruit
. But it doesn't help much, because the conversion between integer and enum value in C is implicit.
All in all, if you need to initialize memory to an enum value other than 0
, you will need to write a loop. If you indeed want the value corresponding to 0
, calloc()
will do, it doesn't matter as 0
is still 0
:)