为什么要使用结构体数组?

考虑这样一种情况,我们需要存储5个学生的数据。我们可以使用以下结构体来存储数据。

#include <stdio.h>
struct student
{
    char name[20];
    int id;
    float marks;
};
void main()
{
    struct student s1, s2, s3;
    int dummy;
    printf("Enter the name, id, and marks of student 1: ");
    scanf("%s %d %f", s1.name, &s1.id, &s1.marks);
    scanf("%c", &dummy);
    printf("Enter the name, id, and marks of student 2: ");
    scanf("%s %d %f", s2.name, &s2.id, &s2.marks);
    scanf("%c", &dummy);
    printf("Enter the name, id, and marks of student 3: ");
    scanf("%s %d %f", s3.name, &s3.id, &s3.marks);
    scanf("%c", &dummy);
    printf("Printing the details....\n");
    printf("%s %d %f\n", s1.name, s1.id, s1.marks);
    printf("%s %d %f\n", s2.name, s2.id, s2.marks);
    printf("%s %d %f\n", s3.name, s3.id, s3.marks);
}

输出

Enter the name, id, and marks of student 1: James 90 90
Enter the name, id, and marks of student 2: Adoms 90 90
Enter the name, id, and marks of student 3: Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000

在上面的程序中,我们在结构体中存储了3个学生的数据。然而,如果有20个学生,程序的复杂性将会增加。在这种情况下,我们将不得不声明20个不同的结构体变量并逐个存储它们。这将始终是一项艰巨的任务,因为每次添加一个学生都必须声明一个变量。同时记住所有变量的名称也是一项非常棘手的任务。然而,C语言使我们能够通过使用结构体的数组来声明结构体数组,从而避免声明不同的结构体变量;相反,我们可以创建一个包含所有存储不同实体信息的结构体的集合。

C中的结构体数组

在C语言中,结构体数组可以被定义为包含多个结构体变量的集合,其中每个变量包含有关不同实体的信息。结构体数组用于存储有关不同数据类型的多个实体的信息。结构体数组也被称为结构体的集合。

1.png

让我们看一个存储5个学生信息并打印的结构体数组的例子。

#include<stdio.h>
#include<string.h>

struct student{
  int rollno;
  char name[10];
};

int main(){
  int i;
  struct student st[5];
  
  printf("Enter Records of 5 students\n");
  
  for(i=0; i<5; i++){
    printf("\nEnter Rollno:");
    scanf("%d",&st[i].rollno);
    printf("\nEnter Name:");
    scanf("%s",&st[i].name);
  }
  
  printf("\nStudent Information List:");
  
  for(i=0; i<5; i++){
    printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
  }
  
  return 0;
}

输出:

Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

标签: c语言, c语言教程, c语言技术, c语言学习, c语言学习教程, c语言下载, c语言开发, c语言入门教程, c语言进阶教程, c语言高级教程, c语言面试题, c语言笔试题, c语言编程思想