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

标签 c arrays initialization compound-assignment

#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] s 未初始化。它们包含不确定的值,使用它们会调用 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) ,至少。

关于c - 数组元素(使用复合赋值运算符后)会产生垃圾值,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39491498/

相关文章:

arrays - Julia 初始化数组/向量不是零而是随机

c++ - 初始化 SDL_Surface 时遇到问题

c++ - 为什么文件范围静态变量必须被零初始化?

python - python 和 c 信号处理程序如何协同工作?

c++ - 在 C++ 中对数组进行二进制搜索

javascript - 在javascript中将浮点值转换为uint8数组

javascript - For循环遍历数组并创建彼此为 sibling 的div

c - 生成文件错误 : unexpected end of line

c++ - 想要为 Windows 8.1 安装 Eclipse for c/c++

C : How to stop the loop when getting the end of input from keyboard or file while using scanf one char at a time