May 21, 2017 at 8:43pm UTC
What does you're compiler tell you is wrong?
In the no argument constructor where are you allocating any memory for that pointer?
In your avg() function you're trying to access 70 elements of an array that possibly doesn't have enough memory allocated for an array with 70 elements.
Why are you mixing array[] notation with *pointer notation to access your arrays? I recommend you stick to array notation.
May 21, 2017 at 8:47pm UTC
it compiles but it crashes
May 21, 2017 at 9:05pm UTC
It must crash!
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class ARRAY
{
protected :
int *a;
public :
ARRAY();
ARRAY(int );
~ARRAY();
void avg();
};
ARRAY::ARRAY()
{
for (int i = 0; i < 70; i++)
{
std::cout << "Immediately before crashing, i == " << i << '\n' ;
std::cout << "Now I'm going to access memory I haven't reserved and...\n" ;
*(a + i) = 0;
}
}
ARRAY::ARRAY(int size)
{
a = new int [size];
for (int i = 0; i < size; i++)
{
*(a + i) = 3 + rand() % 36;
}
}
ARRAY::~ARRAY()
{
delete a;
}
void ARRAY::avg()
{
int counter = 0;
double aveg;
for (int i = 0; i < 70; i++)
{
if (a[i] < 8 && a[i] % 2==0)
{
aveg += *(a + i);
counter++;
}
}
aveg /= counter;
cout << aveg << endl;
}
int main()
{
srand(time(NULL));
int *arr;
ARRAY obj1;
obj1.avg();
return 0;
}
Last edited on May 21, 2017 at 9:06pm UTC