[try Beta version]
Not logged in

 
finding sum of dynamic array in a separate function

Dec 15, 2015 at 12:31am
Can someone please help me debug this code? I've been stuck on this since yesterday. The assignment calls for user to enter any amount of data, then program will calculate average of the data. You have to use a separate average function and use loops in both main and average function. My problem is the program will not cout the sum correctly...Here is my code: http://cpp.sh/8tok
Last edited on Dec 15, 2015 at 3:04am
Dec 15, 2015 at 1:59am
Line 21: Variable length arrays are not part of standard C++.

Line 24: should be cin << values[number];
Dec 15, 2015 at 2:10am
I have to use a variable length array for this assignment to store the integers. And as for line 24 I did that but that gave me a huge error. I'm pretty sure it's supposed to be cin >> values[number]; Can someone else please help?
Dec 15, 2015 at 8:24am
line 24 in your code is correct

C++ requires size to be specified by a constant (as opposed to variable) while declaring arrays.
However, you can declare a int pointer and allocate memory to it.

replace line 21 with
 
int *values  = new int[numOfIntegers];

Last edited on Dec 15, 2015 at 8:25am
Dec 15, 2015 at 11:12am
Dec 15, 2015 at 1:35pm
Doh! Sorry. I meant line 24 should be cin >> values[number];. The point is that currently line 24 always stores the value in the same place (values[numOfIntegers]) which is also an out-of-bounds index into the array.

The other problem is line 7. Remove the semicolon from the end of the line. With the semicolon there, the loop does nothing, then lines 8-10 run once. Since number == size at that point, the access is out of bounds so you get who-knows-what.
Dec 17, 2015 at 2:21am
You're right the problem was with the semicolon, sorry I never really paid attention to what you commented after the guy above suggested declaring an int pointer which I did as I rewrote the code and everything worked fine so I thought problem was with the array but all along my original code didn't work cuz of the semicolon
Topic archived. No new replies allowed.