Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize array of structure in C?

Tags:

c

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 PressureValues 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?

like image 290
Asad Avatar asked Dec 07 '22 22:12

Asad


1 Answers

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.

like image 161
Paul R Avatar answered Dec 29 '22 05:12

Paul R