数组元素(使用复合赋值运算符后)产生垃圾值,为什么?

Array elements (after using compound assignment operator) yields garbage value, why?

#include<stdio.h>
void main(void)
{
    int a[5]={90,78,77,98,98}, b[5]={80,45,67,88,57}, c[5]={88,99,65,55,74},total[3],i,j;
    for(j=0;j<=4;j++)
        {
            total[0]+=a[j];
            total[1]+=b[j];
            total[2]+=c[j];
        }

    for(i=1;i<=3;i++)
    {
    printf("%d행의 가로 합 : %d\n",i,total[i-1]);
    }
}

total[0]total[1] 是正确的值,但 total[2] 是错误的值。我找不到我的错。能解释一下吗?

这里的第一个问题在代码中

        total[0]+=a[j];
        total[1]+=b[j];
        total[2]+=c[j];

您使用 total[n] 未初始化的地方。它们包含不确定的值,使用它们会调用 undefined behavior.

详细说明,total是一个未初始化的自动局部变量,数组元素的初始值是不确定的。通过在这些元素上使用 += 运算符,您试图 读取 (使用)不确定的值,因此它会在您的情况下调用 UB。

来自 C11 的相关引述,第 §6.5.16.2 章,复合赋值

A compound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1 has an atomic type, compound assignment is a read-modify-write operation with memory_order_seq_cst memory order semantics.

因此,通过对未初始化的值使用 +=,_您正在尝试读取( 或使用 )具有不确定值的变量,这会导致 UB .

如果需要,您可以使用类似

的语法来初始化整个数组
  int total[3] = {0};

将数组的 所有 元素初始化为 0,这基本上是您所期望的。

也就是说,void main(void) 不是托管环境中 main() 的一致签名,根据规范,它至少应该是 int main(void)