C Structure
The structure is a user-defined data structure that is used to bind two or more data types or data structures together. Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Create a Structure
To create a structure in C, the struct keyword is used followed by the tag name of the structure. Then the body of the structure is defined, in which the required data members (primitive or user-defined data types) are added.
To create the structure, you must create a variable of it.
Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable:
Create a struct variable with the name "s1":
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Initialize Structure
Initializing a structure member means assigning values to the structure members according to their respective data types. There are three ways to initialize structure members:
- Using dot '.' operator
- Using curly braces ‘{}’
- Designated initializers
1.Using Dot '.' operator
Using the dot (.) operator, we can access any structure member and then initialize or assign its value according to its data type.
Struct structure_name variable_name;
Variable name.member = value;
Student Section : A
2.Using curly braces ‘{}’
If we want to initialize all the members during the structure variable declaration, we can declare using curly braces.
Struct structure name v1 = {value, value, value, ..};
3.Designated initializers
Designated initialization is simple initialization of the structure members and normally used when we want to initialize only a few structure members, not all of them.