C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
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结构数组
让我们查看一个存储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;  
}  
输出:
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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4