Error in Output

Hello I'm having a problem with one of my programs the point of the program was to use pointers instead of array indexing to add all the integers of a particular array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int add(int *r)
{
    int total;
    for (int n = 0; n<4;++n)
    {
        total += *(r+n);
    }
    return total;
}

 
int main()
{   
    int trial[]={1,2,3,4};
    int *p;
    p = trial;
    for (int n = 0; n<4;++n)  // if removed the code suddenly bugs :|
    {
      cout << *(p+n) << endl;
    }
    cout << add(p) << endl;
    system ("pause");
    return 0;    
}


The weird thing about this is without the code
1
2
3
4
for (int n = 0; n<4;++n)  
    {
      cout << *(p+n) << endl;
    }


It suddenly outputs the wrong number. :( I think I got the function right but I don't exactly know where the problem lies
Sorry, my point was wrong.
Last edited on
I don't see anything wrong with it but I might be missing something. The pointer arithmetic looks ok, I think. Could you paste the output here?
Oh alright I'll try that :D

Uhm the output is 18 when I run it without this code

1
2
3
4
for (int n = 0; n<4;++n)  
    {
      cout << *(p+n) << endl;
    }
total is not initialized to zero.
closed account (S6k9GNh0)
@manasij7479, that's incorrect, please correct it. In pointer arithmetic, the size of the data pointed too has nothing to do with the size of a pointer.
Last edited on
Thanks for pointing that out.
Topic archived. No new replies allowed.