在c++中数组没有按预期填充
Arrays not filling in as expected in C++
我昨天才开始尝试学习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给出了,所以我不在这里写
祝你继续学习顺利。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用用户输入在C++中正确填充2D数组
- 如何找到大小'x'数组是否完全填充,在C++?
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 通过for循环使用用户输入填充列表
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 如何正确填充在堆上分配的二维数组?
- 将数字转换为填充字符串
- 有没有办法在一行中填充矢量图
- 用C++中的数字和条件填充向量
- 用真值填充矢量
- 使用结构成员指针在C++中填充结构
- 流填充字符的默认定位
- 使用不同算法的 PKCS1v15 填充进行加密 ++ 签名
- C++:使用缓冲区中的数据填充结构
- 如何将零填充的多维数组传递给 C++ 中的函数?
- Cryptopp:获取密码输入的填充字符串
- 填充上编译器生成的复制构造函数之间的不一致
- RcppEigen 模板化函数,用于填充单位法线
- 我想生成许多矩阵并用随机数填充它