Sum of array elements in a dynamic array

I'm trying to sum the elements in a dynamic array. This is the code thus far.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstdlib>
using namespace std;

void fillarray(int SIZE);

int main(int argc, char *argv[])
{
    int size;
    
    cout<<"\nEnter the desired size of the array: ";
    cin>>size;
    
    fillarray(size);
    
    system ("pause");
    return EXIT_SUCCESS;
}

void fillarray(int SIZE)
{
     int *arr;
     arr = new int[SIZE];
     int total = 0;
     int average;
     
     for (int i=0; i < SIZE; i++)
     {
         cout<<"\nEnter a number to be stored in array element "<<i+1<<": ";
         cin>>arr[i];
     }
     
     for (int i = 0; i < SIZE; i++, arr++)
     {
         cout<< *arr <<" ";
     }
     
     int *p = arr;
     for (int i = 0; i < SIZE; i++, p++)
     {
         total += *p;
     }
     cout<<"\n"<<total<<endl;   
     
     delete arr;
     arr = NULL;    
}


The problem lies with the output for "total." For some reason it's being output in machine code.



Enter the desired size of the array: 3

Enter a number to be stored in array element 1: 4

Enter a number to be stored in array element 2: 5

Enter a number to be stored in array element 3: 6
4 5 6
-1480403165
Press any key to continue . . . 


It would be helpful if anyone could shed light on this issue. Thanks!
When you increment the value of arr at line 33, this means the arr points beyond the last element of the array. Then you assign p to that. That means that p points beyond the last element also. When you try and dereference a pointer that points to unallocated memory, crazy things will happen. In this case, the value of (*p) will be uninitialised (essentially random). Instead of incrementing arr in line 33, use the same syntax you used in line 30 to input the numbers, i.e. arr[i]. This way doesn't change the value of arr.
closed account (zb0S216C)
Night Rawk wrote:
delete arr;

Careful! This causes a memory leak. A call to new should have a corresponding call to delete. A call to new[] should have a corresponding call to delete[].

You've done something terrible here. In your second for loop in fillarray(), arr, which each cycle, is moved 1 place up through the array. When the loop ends, arr is pointing to the to the last element of the dynamically allocated array; thus, p points to the last element of the dynamically allocated array. As a consequence, the 3rd loop moves p past the dynamically allocated array, and ultimately, reads uninitialised memory (usually contains values such as 82847324).

Wazzak
Last edited on
Thank you slicedpan! It now works perfectly!
Topic archived. No new replies allowed.