Hi:

I posted yesterday about setting my loop to get random number between the values I desire. Now I got a bit of misunderstanding with my arrays. In the program now I am trying to calculate the average sum of the amount of numbers I get each series. My problem seems to be that I need to clear my time_series_average array. I try deleting it but I got the following error:

How long you want your series: 5
How many times do you want to run the series: 5
0.6
a.out(249) malloc: *** error for object 0x7fff5fbff780: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap

So I got two questions:

1) How do I set up the loop so it calculate the average for each time_series_average without adding the next.
2) A bit out of context but how can I get C++ to give a random number without starting with the same number always. I notice when I cout the list of numbers, it is always the same list.

Thanks for your help and here is my code.

G

//Program name = random.cpp
#include <cstdlib>
#include <iostream>

using namespace std;

int number_generator();
int main()
{
int series;
double average, sum, times;
double series_number[1000001];
double time_series_average[100];
cout << "How long you want your series: ";
cin >> series;
cout << "How many times do you want to run the series: ";
cin >> times;

for (int j=0; j<times; j++)
        {
        for (int i=0; i<series; i++)
                {
                int number_to_use = rand() % 999;
                double actual_random_integer = number_to_use/100;
                if (actual_random_integer > 0.25)
                        {
                        series_number[i] = 1;
                        }
                else
                        {
                        series_number[i] = -1;
                        }
                sum+=series_number[i];
                }
        time_series_average[j] = sum/series;
        cout << "( " << j  <<  " )"  << time_series_average[j] << endl;
        //delete [] time_series_average;
        }
//cout << sum << endl;
average = sum/series;
cout << "Average of series = " << average << endl;
}

lines 12 and 13. You can not allocate or delete those arrays yourself. If you want to clear out the values then just set them all to 0. memset() is the quickest way to do it, but there are other ways too. memset(series_number, 0, sizeof(series_number)); And before anybody complains, yes I know there are a few odd-ball operating systems which the memset() will not work correctly. But those are the extreme exceptions. Most, if not all, of us here on DaniWeb use either MS-Windows, *nix, or MAC.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.