c - 在 C 中使用特定值初始化动态分配的数组

标签 c arrays dynamic-allocation

所以,我为一个数组动态分配了内存,我想将它的所有值初始化为一个特定值(这是一个枚举的元素)。

这是我到目前为止所做的:

    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 use memset()?

没有。 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/

相关文章:

c - 字符串正在打印奇怪的字符 - lex 中的 c 代码

c - 如何将数据存储在动态结构数组中?

c - 不是指针,无法取消引用

java - 将 BST 转换为数组

c - C 中的逻辑相等

arrays - 如何在 Ruby 中连接两个数组中的值

c - 使用嵌套循环翻转C中的数组元素数据

c++ - 如何在Matlab中正确使用C++ dll中动态分配的内存

c - 列出 header 中声明但源文件中缺失的所有函数?

c - 如何在微 Controller 上使用外部存储器