Write a C program declare, initialize and access array of structure. In this post, I will explain how to declare, initialize and access array of structure in C programming. We will learn different ways of initializing structure array and accessing its.
Required knowledge
Basic C programming, Loop, Array, Structures
In previous post we discussed how to declare and use structures in C language. Hence, I would not go deep discussing about basics of structures declaration.
How to declare array of structure?
Structure array declaration follows the normal array declaration syntax. Since, array of structure is a normal structure object only. Which we can declare structure array in two ways.
Declare array of structure along with structure declaration
The following code declares a structure to store student details. Along with the structure declaration it declares an array of structure object to store 100 student details.
Declare array of structure after structure declaration
The following code declares a student structure as we did above. After structure declaration it declares an array of student structure, capable of storing 100 student marks.
How to initialize structure array?
Structure array initialization follows same syntax as you initialize single structure object. The only difference is here you can initialize more than one structure object at a time.
Example:
How to access array of structure?
To access any structure object, you need to combine array indexed and structure member accessing technique. You can use either dot . or arrow -> (for pointers) operator to access structure array.
Example:
The above code assigns data to first array object. You can also use loop to iterate for all array object.
Program to declare, initialize and access array of structure
Output
Enter 5 student details Student 1 name: Pankaj Student 1 roll no: 12 Student 1 marks: 89.5 Student 2 name: Sweety Student 2 roll no: 15 Student 2 marks: 98.0 Student 3 name: Raani Student 3 roll no: 17 Student 3 marks: 90.0 Student 4 name: Bakhtawar Hameed Student 4 roll no: 2 Student 4 marks: 92.0 Student 5 name: Moody Student 5 roll no: 9 Student 5 marks: 60.2 Student details --------------------------- Name : Pankaj Roll : 12 Marks: 89.50 --------------------------- Name : Sweety Roll : 15 Marks: 98.00 --------------------------- Name : Raani Roll : 17 Marks: 90.00 --------------------------- Name : Bakhtawar Hameed Roll : 2 Marks: 92.00 --------------------------- Name : Moody Roll : 9 Marks: 60.20 ---------------------------
Happy coding