Reputation: 11
In this program I am asked to work with a certain number of values that are stored in a file.txt.
I have a class that has a public function called Absolute_frequency that returns a pointer to an array created in the function called abs_freq[]. My problem is that I now need to save this array into another array in my main.
int *Data::Absolute_frequency() {
/*Here I created 2 arrays that store values representing max and min limit
of certain intervals (eg. 0 to 20, 21 to 40, 41 to 60, etc...)
And then I run my code thru each of these intervals and count how many
values are in them, and store it in abs_freq[]:*/
int *abs_freq=new int [num_intervals]();
for (int j = 0; j < num_values; j++)
{
for (int i = 0; i < num_intervals; i++)
{
if (values[j] >= intervals_min[i] && values[j]<=intervals_max[i])
{
abs_freq[i]++;
}
}
}
return abs_freq;
}
From what I have tested, the array abs_freq[i] is storing what is suposed, now my problem is that I need to pass this array into my main(). I tried something like this but as I was expecting, it only passed the 1st value of abs_freq:
int main(){
Data data;
int *absolute_freq = new int[num_intervals]();
...
for (int i = 0; i < num_intervals; i++)
{
absolute_freq[i] = *data.Absolute_frequency();
}
for (int i = 0; i < num_intervals; i++)
{
printf("Absolute frequency interval %d: %d \n", i+1,absolute_freq[i]);
}
....
}
How can I store the entire array instead of just the 1st value?
Upvotes: 0
Views: 54
Reputation: 409166
You do it by having a pointer variable in the main
function, and initialize it with the pointer returned by the function:
int* absolute_freq = data.Absolute_frequency();
Remember that once you're done with the array you have to delete[]
it.
Upvotes: 3
Reputation: 35154
In your code for (int i = 0; i < num_intervals; i++) { absolute_freq[i] = *data.Absolute_frequency() ...
, you call function Absolute_frequency
again and again, each time creating a new array of integers (which you do not free). Further, *data.Absolute_frequency()
is equivalent to data.Absolute_frequency()[0]
, i.e. it always gives you the first entry in the array.
Not sure what you actually have to achieve; but I suppose the following code would be better:
int *absolute_freq = data.Absolute_frequency();
for (int i = 0; i < num_intervals; i++)
{
printf("Absolute frequency interval %d: %d \n", i+1,absolute_freq[i]);
}
delete[] absolute_freq;
Upvotes: 0