Structs and Arrays in C

In this lesson, you will learn about the array of structures in C, how to declare and initialize them, along with examples, to better understand the topic.

Declaring an Array of Structures in C

Consider the struct below:

struct student {
  char name[20];
  int age;
  char grade[1];

};

Now declaring an instant of this struct.

struct student student_arr [10];

Initializing an array of struct in C

An array of structs can be initialized when initiated.

struct student student_arr[4] = {
    {"Andy", 23, 'B'},
    {"Steve", 25, 'A'},
    {"John", 25, 'C'},
    {"Mike", 21, 'A'}
};

Example of an Array of Structs in C

#include<stdio.h>

#include<string.h>

struct student {
  char name[20];
  int age;
  char grade[1];
};

int main() {
  struct student student_arr[5];

  for (int i = 0; i < 3; i++) {

    printf("Enter student Name: ");
    scanf("%s", student_arr[i].name);

    printf("Enter student Age: ");
    scanf("%d", & student_arr[i].age);

    printf("Enter Grade: ");
    scanf("%s", & student_arr[i].grade);
  }

  printf("\n");

  printf("Name\tAge\tGrade\n");

  for (int i = 0; i < 3; i++) {
    printf("%s\t%d\t%s\n",
      student_arr[i].name, student_arr[i].age, student_arr[i].grade);
  }

  return 0;
}

Output

Enter student Name: Fred
Enter student Age: 26
Enter Grade: C

Enter student Name: Clara
Enter student Age: 24
Enter Grade: B

Enter student Name: Mike
Enter student Age: 21
Enter Grade: A

Name Age Grade

Fred 26 C

Clara 24 B

Mike 21 A


Summary

  • An array of structures is a collection of structures.
Back to: Learn C Programming > Structures and Unions

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.