带指针的数组求和我在求和中遇到问题

Array Sum with Pointers i have a problem in the sum

本文关键字:求和 遇到 问题 数组 指针      更新时间:2024-09-22

我有这段代码。我有一个问题。当我为这些数字"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(。

需要注意的是,您正在重新声明ij

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