struct TheData
{
double* Values; // holds the data to be filtered
unsignedlong Length; // number of data values
bool Valid; // true if the data values have been Valid by the user
};
and i need to initialize the structure where i keep all the data. I am wondering what are the ways to initialize Values bit?
I have a working solution but it doesnt really fit the task that was set :
#include <iostream>
usingnamespace std;
struct TheData
{
double* Values; // holds the data to be filtered
unsignedlong Length; // number of data values
bool Valid; // true if the data values have been Valid by the user
};
void EnterData(TheData&);
int main()
{
TheData OriginalData = {0,0,false};
EnterData(OriginalData);
cout << endl;
delete [] OriginalData.Values;
}
// Allow the user to enter the data to be filtered
// Arguments:
// (1) the structure containing the input data
// Returns: nothing
//
void EnterData(TheData& Data)
{
// initialize the data structure that holds the data to be filtered, including getting
// the number of data values from the user
cout << "Please enter the number of data values to be filtered:" << endl;
cin >> Data.Length;
cout << endl;
Data.Values = (double*)malloc(sizeof(double)*Data.Length);
for (unsignedint i=0; i<Data.Length; i++)
{
Data.Values[i] = 0;
}
// allocate memory to the data
// <enter code here>
}
As you can see i first allocate memory and then initialize... but the task is to initialize first and I have no idea how to do this before allocating the memory for the pointer. Are there any ways?
What you are doing is correct, and the only way for this to work really. The problem is you are mixing malloc() and delete. Use new/delete or malloc()/free(). Don't mix them or you could have trouble.
yes. I can then allocate memory for the values. I asked my teacher and he says setting array to zero is not what he ment under 'initialization'. He ment something else there....lol
so what can be the options if i have
1 2 3 4 5 6
struct TheData
{
double* Values; // holds the data to be filtered
unsignedlong Length; // number of data values
bool Valid; // true if the data values have been Valid by the user
};
and I need to // initialize the data structure that holds the data to be filtered
It's so hard to guess.... I just have no idea, because for me initializations means removing rubbish from memory and preparing place....
Btw it was already initialized by him here TheData OriginalData = {0,0,false};
Really confused what I was ment to do in the function...how to initialize the structure if it is already initialized
Since you seem to be using C++, you could use what is called a constructor to do it for you. Besides what you already did, manually setting it after creating the object is really the only other way.