【问题标题】:How to initialize all values of array in structure in c如何在c中初始化结构中数组的所有值
【发布时间】:2023-03-31 12:23:02
【问题描述】:

我需要将数组的所有值初始化为 0。newCount->numbers[1] = {0} 给出错误“预期表达式”。我该怎么办?

typedef struct count *Count;

struct count{
    int numbers[101];
    int totalCalls;
    int totalCallsEach[101];
};

Count create_Count(void){
    Count newCount = malloc(sizeof(struct count));
    newCount->numbers[101] = {0};
    newCount->totalCalls = 0;
    return newCount;
}

【问题讨论】:

    标签: c arrays structure


    【解决方案1】:

    使用memset 将数组的值设置为0

    memset(newCount->numbers, 0, sizeof(newCount->numbers));
    memset(newCount->totalCallsEach, 0, sizeof(newCount->totalCallsEach));
    

    附言

    typedef struct count *Count;
    

    不是一个好的typedef。使用:

    typedef struct count Count;
    

    typedef struct count *CountPtr;
    

    【讨论】:

    • 看起来Countcount * 的一种类型...所以newCount 是一个指针
    • 遗憾的是,OP 在结构上使用了 typedef,其中 typedef 创建了 Count 作为指针,因此不需要额外的 '*'。对我来说,答案中的 oops 只是另一个不在结构上使用 typedef 的原因。
    【解决方案2】:

    如果您在分配对象时需要将数组初始化为全位 0,请使用 calloc 而不是 malloc

    newCount = calloc( 1, sizeof *newCount );
    

    这也会将 totalCallstotalCallsEach 成员初始化为 all-bits-0。

    如果您想将所有元素设置为任何其他值而不遍历每个元素,则需要使用memset

    样式说明:通常,将指针隐藏在typedef 中并不是一个好主意。如果使用Count 类型对象的任何人都需要了解它的指针性(即,他们需要使用-> 运算符而不是. 来访问成员),那么最好这样做

    typedef struct count Count;
    ...
    Count *create_count(void)
    {
      Count *new_count = ...;
      ...
    }
    

    IOW,在声明中明确指定对象的指针。

    如果您不打算让任何人直接取消引用或访问 Count 对象的成员,并提供用于设置、获取和显示成员的 API,例如

    myCount = createNewCount();
    deleteCount( myCount );
    x = getTotalCalls( myCount );
    addCount( myCount, value );
    printf( "myCount = %s\n", formatCount( myCount ) );
    

    等等,那么可以将指针隐藏在 typedef 后面。

    【讨论】:

      【解决方案3】:

      您可以使用memset (doc)

      memset(newCount->numbers, 0, 101*sizeof(int));
      

      【讨论】:

        【解决方案4】:

        struct count *newCount = (struct count *)calloc(1,sizeof(struct count))

        代替 malloc 使用 calloc,它会创建一个“struct count”大小的内存并将其初始化为零。

        【讨论】:

        猜你喜欢
        • 2022-01-05
        • 2012-01-22
        • 1970-01-01
        • 2010-09-23
        • 2010-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多