How to initialize an array of structure in C?

The scenario is that I have a definition of a nested structure, and I have an array of 10 such structures. I want to initialize each element of the parent and child structure with zero. The code is below:

struct PressureValues { float SetPressure; float ReadPressure; }; struct CalibrationPoints { float SetTemperature; struct PressureValues PressurePoints[10]; }; extern volatile struct CalibrationPoints code IntakeCalibrationPoints[10]; extern volatile struct CalibrationPoints code DischargeCalibrationPoints[10]; 

I know a long method to initialize each element of the structure from scratch using a loop, but I'm looking for a short method to initialize all elements to zero. Or what is the default initialization value for an array of structure (containing only floating point numbers), is it zero or any random value?

+4
source share
4 answers
 volatile struct CalibrationPoints IntakeCalibrationPoints[10] = { { 0 } }; volatile struct CalibrationPoints DischargeCalibrationPoints[10] = { { 0 } }; 

This will initialize all elements to zero.

The reason this works is because when you explicitly initialize at least one element of the data structure, then all other elements that do not have the specified initializers will be initialized to zero by default.

+11
source

Firstly, I think you have a misconception about what โ€œintializeโ€ means.

You see that when the system gives your program memory, it does not bother to clean up after the last program used. That way you can get zeros, you can get seemingly random values, etc.

Now your structures can not benefit from the fact that their data is accidentally installed, right? So, you initialize them: you give your members significant values โ€‹โ€‹that make sense for your data. It can be all zeros or not. Initialization, so to speak, sets a meaningful default value .

As for your question, you can use memset() to quickly fill in zero. Hooray! Hope I helped.

memset() : http://www.cplusplus.com/reference/clibrary/cstring/memset/

+2
source

you can use

 memset(IntakeCalibrationPoints, 0x00, sizeof( IntakeCalibrationPoints)) 

eg

+1
source

you can try:

 struct CalibrationPoints struct; memset ( struct, 0, sizeof(CalibrationPoints)); ` 
+1
source

Source: https://habr.com/ru/post/1346526/


All Articles