Get to know this derived data type, and learn how to use structures in C in this blog.
Introduction
Last time, you learned about organizing data using array variables in C. However, the elements in an array only have one type. This means the elements could only be purely ints, chars, longs, strings, etc. But what if you want to add more variety or different types to your data set? Here is where structures come in handy, and you’ll learn how to use structures in C here.
What is a Structure in C?
A structure in C is composed of organized data types assigned by the user. Organized, meaning the user can pick his or her own data type set. For example, you can assign a structure to contain floats, integers, and boolean data types. Here is an illustration:
Additionally, structures reside in contiguous memory locations. With this, you can easily use pointers to point to structures and help you with various memory allocation applications.
Â
How to Use a Structure in C
Prototype the Structure
You simply use the struct identifier, the structure name, curly braces, and the data types you want to use.
struct struct_name {
datatype_1 var_1;
datatype_2 var_2;
.
.
datatype_n var_n;
};
Declare Structure Variable
Next, declare that struct type to a structure variable:
struct_name struct_var;
Access its members
You can easily access the structure members in the body of your program through the dot (.) operator.
struct_var.var_1 = some_data;
struct_var.var_2 = some_data;
struct_var.var_3 = some_data;
Using Type Definition to Declare a New Type from a Structure
You can also create a new data type from a structure. This sometimes make it easier to pass the structure as parameters to functions.
Prototype the Structure with typedef
typedef struct_name_tag {
datatype_1 var_1;
datatype_2 var_2;
.
.
datatype_n var_n;
} struct_name_t;
Declare a New Instance of the Data Type
struct_name_t struct_name;
Access Members of the Structure
struct_name.var_1 = some_data;
struct_name.var_2 = some_data;
struct_name.var_3 = some_data;
Example Application
For example, if you’re trying to measure voltages from a set of ports and also monitoring a switch status on those ports, it would make sense to organize data by ports as a structure as:
Structure Prototype
struct port_data_t {
float volt_12V;
float volt_5V;
int sw;
}
Structure Declarations
struct port_data_t port_data1, port_data2;
Access its Members
port_data1.volt_12V = ADC_value[0];
port_data1.volt_5V = ADC_value[1];
port_data1.sw = SW_value;
Conclusion
Structures are a great way to organize data, even with different data types. Additionally, the contiguous memory location of the structure data type makes it flexible in pointer-specific applications.