为什么带有int字段的结构类型"忘记"第一次围绕for循环后它是什么值?

-1 c for-loop

为什么以下代码仅适用于围绕for循环的第一次迭代?

typedef struct {
    char name[3];
    int gold, silver, bronze, total;
} tally_t;

int main(void)
{
    tally_t country[COUNTRIES_COMPETING];
    int j;
    j=0;
    country[j].gold=0;
    for (j=0; j<5; j++) {
        country[j].gold++;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

这是因为你只初始化了数组第一个元素的gold成员.所有其余的都未初始化并且具有未定义的值.更改未定义的值是未定义的行为.

  • `tally_t country [COUNTRIES_COMPETING] = {{0}};`将在数组中将所有内容初始化为0. (3认同)