在c++中数组没有按预期填充

Arrays not filling in as expected in C++

本文关键字:填充 c++ 数组      更新时间:2023-10-16

我昨天才开始尝试学习c++,我近期的目标之一是制作一个矩阵乘法函数。

在尝试之前,我想感受一下数组是如何工作的,所以我做了一个简单的程序,应该制作两个数组来表示(数学)三维空间中的向量,并取它们的点积。下面是我写的代码:

/*Initializing two vectors, v1 and v2*/
int v1[3] = { 0 }; 
int v2[3] = { 0 };
int sum = 0; //This will become the sum for the dot product
int i=0; //counter for the following loop
for(; i<3; ++i)
    v1[i] = v2[i] = i+1; //This should make both vectors equal {1,2,3} at the end of the loop
    sum += v1[i]*v2[i]; //Component-wise, performing the dot product operation
std::cout<< sum <<std::endl;
return 0;

当代码运行完成后,输出应该是1*1 +2*2 +3*3 = 14

然而,输出实际上是647194768,这似乎没有任何意义。我从一些朋友那里听说,在c++中,如果你不小心初始化数组,那么就会发生一些疯狂的事情,但是我完全惊呆了,这么简单的事情怎么会搞得这么糟糕。

你能提供一些更深入的见解,为什么会发生这种情况,以及c++的逻辑是什么导致的?

您不小心将sum +=行放在for循环之外。这是因为在循环中没有大括号。所以只有第一行v1[i]...包含在for循环中。像这样修改:

/*Initializing two vectors, v1 and v2*/
int v1[3] = { 0 }; 
int v2[3] = { 0 };
int sum = 0; //This will become the sum for the dot product
for(int i=0; i<3; ++i)
{
    v1[i] = v2[i] = i+1; //This should make both vectors equal {1,2,3} at the end of the loop
    sum += v1[i]*v2[i]; //Component-wise, performing the dot product operation
}
std::cout<< sum <<std::endl;
return 0;

注意在for循环语句周围使用了大括号{ .. }。现在给出正确答案:14.

当你问更深入的见解在这里我写一些解释你的代码

int v1[3] = { 0 }; 
int v2[3] = { 0 };

用0初始化v1和v2,

int sum = 0; //This will become the sum for the dot product

这里用0初始化sum (GOOD)

int i=0; //counter for the following loop
for(; i<3; ++i)
    v1[i] = v2[i] = i+1; //This should make both vectors equal {1,2,3} at the end of the loop
    sum += v1[i]*v2[i]; //Component-wise, performing the dot product operation

这里你犯了一个错误,因为你没有提供{…}编译器将考虑循环语句中的第一个列表。像下面的

v1[0] = v2[0] = 0+1
v1[1] = v2[1] = 1+1
v1[2] = v2[2] = 2+1

现在第二行将出现在图片中,注意,现在i变成了3

sum += v1[i]*v2[i];

在这里,你试图访问数组的无效位置(第四个)这就是为什么你得到647194768
你得到的是垃圾价值


正确的代码已经由metacubed给出了,所以我不在这里写
祝你继续学习顺利。