The scenario is that I have nested structure definition, and I have an array of 10 such structure. What I want is to initialize each of the element of both parent and the child structure with zero. Code is given below:
struct PressureValues
{
float SetPressure;
float ReadPressure;
};
struct CalibrationPoints
{
float SetTemperature;
struct Pr开发者_Python百科essureValues PressurePoints[10];
};
extern volatile struct CalibrationPoints code IntakeCalibrationPoints[10];
extern volatile struct CalibrationPoints code DischargeCalibrationPoints[10];
I know the lengthy method of initializing each structure element with zero using loop, but I am looking for a short method of initializing all elements to zero. Or what is the default initialize value of array of structure (containing floats only), is it zero or any random value?
volatile struct CalibrationPoints IntakeCalibrationPoints[10] = { { 0 } };
volatile struct CalibrationPoints DischargeCalibrationPoints[10] = { { 0 } };
This will initialise all elements to zero.
The reason that this works is that when you explicitly initialise at least one element of a data structure then all remaining elements which do not have initialisers specified will be initialised to zero by default.
First, I think you have a wrong notion of what 'intialize' means.
You see, when the system gives your program memory, it doesn't bother to clean up after the last program that used it. So, you can get zeroes, you can get seemingly random values, etc.
Now, your structures can't benefit from their data being randomly set, can they? So you initialize them: you give their members meaningful values, that make sense for your data. That can be all zeroes, or not. Initializing is setting a meaningful default, so to speak.
As for your question, you can use memset()
to quickly zero-fill memory. Cheers! Hope I helped.
memset()
: http://www.cplusplus.com/reference/clibrary/cstring/memset/
You can use
memset(IntakeCalibrationPoints, 0x00, sizeof( IntakeCalibrationPoints))
for example
you can try:
struct CalibrationPoints struct;
memset ( struct, 0, sizeof(CalibrationPoints));
`
精彩评论