带指针的数组求和我在求和中遇到问题
Array Sum with Pointers i have a problem in the sum
我有这段代码。我有一个问题。当我为这些数字"1,1,1,1,1"
运行它时,它回答我是对的,但当我使用这些数字"2,1,3,2,2"
或任何其他数字时,它答错了。问题出在哪里?
#include <iostream>
using namespace std;
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
p = &array1[j];
for (int i = 0; i < size; i++) {
cout << "give next number";
cin >> array1[i];
cout << "n";
}
cout << "the array is:"
<< "n";
for (int j = 0; j < size; j++) {
cout << array1[j] << "n";
sum = sum + *p;
}
cout << "the sum of array elements is: " << sum;
return 0;
}
所以有一个问题
p = &array1[j];
您正在做的是获取数组的第三个CCD_元素的地址。在您的情况下,j
未初始化,这会导致UB,因为j
可能包含任何变量。
要解决此问题,可以将j
初始化为0
(j = 0
(。或者只获取数组中第一个元素的地址,您可以执行以下操作:
p = array;
然后是你的循环,这是arr[j]
地址的峰值,正如我上面所说的UB。
cout << "the array is:" << "n";
for (j = 0; j < size; j++) {
cout << array1[j] << "n";
sum = sum + *(p + j);
}
您的问题是一直在添加array1[0]
。(也就是说,如果将j
初始化为0
(。
需要注意的是,您正在重新声明i
和j
int i, j, *p;
...
for (int i = 0; ...)
...
for (int j = 0; ...)
你可以只做
for (i = 0; ...)
...
for (j = 0; ...)
将已声明的变量设置为CCD_ 15。
这是整个程序:
#include <iostream>
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
// p = &array1[j]; // UB j not initialized but used
/* solution 1
j = 0;
p = &array1[j]
*/
// solution 2 which is same as solution 1
p = array1; // gets address of array[0]
for (i = 0; i < size; i++) { // no need for `int` in front of i
// i is already declared above
// my preference is to declare i here
// and remove declaration above
std::cout << "give next number";
std::cin >> array1[i];
std::cout << "n";
}
std::cout << "the array is:"
<< "n";
for (j = 0; j < size; j++) { // same as above
std::cout << array1[j] << "n";
sum = sum + *(p + j);
}
std::cout << "the sum of array elements is: " << sum;
return 0;
}
输入:
give next number5
give next number4
give next number3
give next number2
give next number1
输出
the array is:
5
4
3
2
1
the sum of array elements is: 15
相关文章:
- 编译包含字符串的代码时遇到问题
- 遇到新行时,有没有办法停止istream_iterator
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 在 for 循环中查找问题时遇到困难
- 创建结构的数组时遇到分段错误
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为什么我遇到分段错误?
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 这些是什么样的错误?即使我不在 Linux 上工作,我也遇到了 Linux 错误
- 求和 int 乘以双倍时的欠/过近似
- 为什么我在尝试模板时遇到视觉工作室C++错误
- 如何从文本文件中读取数值,直到遇到字符类型?
- 从其他类访问类时遇到问题
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 打印问题.我在数组中打印值时遇到一些问题
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 递归求和任务的错误答案
- 使用静态成员声明类时遇到问题
- 在进行基本求和时遇到编译器错误