c的结构体数组

本文概述

  • 为什么要使用结构数组?
  • C语言中的结构数组
为什么要使用结构数组?考虑一种情况,我们需要存储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中的结构数组定义为多个结构变量的集合,其中每个变量都包含有关不同实体的信息。 C语言中的结构数组用于存储有关不同数据类型的多个实体的信息。结构的阵列也称为结构的集合。
c的结构体数组

文章图片
让我们看一个存储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"); 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; }

【c的结构体数组】输出:
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:SarfrazStudent Information List: Rollno:1, Name:Sonoo Rollno:2, Name:Ratan Rollno:3, Name:Vimal Rollno:4, Name:James Rollno:5, Name:Sarfraz

    推荐阅读