# Array Sum with Pointers i have a problem in the sum

I have this code. and I have a problem with it. When I run it for these numbers `"1,1,1,1,1"` it answers me right but when I use these numbers `"2,1,3,2,2"` or any other numbers it answers me wrong. What is the problem?

``````#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;
}
``````

## 1 answer

• answered 2021-05-15 18:15

So you have one problem

``````p = &array1[j];
``````

What you are doing is taking the address of `j`th element of an array. In you case `j` is uninitialized which leads to UB since `j` might contain any variable.

To fix this you can initialize `j` to `0` (`j = 0`). Or to just get an address of first element in array you can do following:

``````p = array;
``````

Than comes your loop, which is summit value at address of `arr[j]` which is UB as I stated above.

``````cout << "the array is:" << "\n";
for (j = 0; j < size; j++) {
cout << array1[j] << "\n";
sum = sum + *(p + j);
}
``````

Your problem here was that you were adding `array1` all the time. (That is if you initialized `j` to `0`).

Other things to note is that you are re declaring `i` and `j`

``````int i, j, *p;
...
for (int i = 0; ...)
...
for (int j = 0; ...)
``````

You could do just

``````for (i = 0; ...)
...
for (j = 0; ...)
``````

to set already declared variables to `0`.

Here is entire program:

``````#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
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;
}
``````

input:

``````give next number5

give next number4

give next number3

give next number2

give next number1
``````

output

``````the array is:
5
4
3
2
1
the sum of array elements is: 15
``````