Structure with Array in C

The array of structures are most commonly used in C language. To declare an array of structure first we need to define a structure and then declare the structure variable as an array. The syntax is as follows :
 struct structure_name structure_variable[N];
where N represents number of array element. Now lets see an example :
struct students {
  char name[30];
  int age;
};
 
struct students std[4];
At above code, the structure variable std defined as an array of 5 elements. Now we can access the each specific structure variable by using its index number. For example :
 stud[0].name;
 stud[1].name;
 stud[2].name;
 stud[3].name;
Now lets see the C code example :
#include <stdio.h>
#include <string.h>

struct students {
  char name[30];
  int age;
};

int main() {
  struct students stud[5];

  strncpy(stud[0].name, "John", 30);
  stud[0].age = 20; 
  strncpy(stud[1].name, "Marry", 30);
  stud[1].age = 18;
  strncpy(stud[2].name, "Sam", 30);
  stud[2].age = 25;
  strncpy(stud[3].name, "Peter", 30);
  stud[3].age = 16;
  strncpy(stud[4].name, "Luci", 30);
  stud[4].age = 19;

  printf("Student Details :\n\n");
  int x;
  for(x=0;x<5;x++) {
    printf("Name : %s\n", stud[x].name);
    printf("Age : %d\n", stud[x].age);
  }   

  return 0;
}
Output :

Student Details :

Name : John
Age : 20
Name : Marry
Age : 18
Name : Sam
Age : 25
Name : Peter
Age : 16
Name : Luci
Age : 19


Next Topic :