C语言 - Struct数组

C语言 - Struct数组 首页 / C语言入门教程 / C语言 - Struct数组

考虑一种情况,我们需要存储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 Learnfk 90 90  
Enter the name, id, and marks of student 2 Toolfk 90 90  
Enter the name, id, and marks of student 3 Chromefk 90 90       
Printing the details....        
Learnfk 90 90.000000                          
Toolfk 90 90.000000                      
Chromefk 90 90.000000 

在上面的程序中,我们在结构中存储了3个学生的数据。但是,如果有20名学生,则该程序的复杂性将增加。在这种情况下,我们将必须声明20个不同的结构变量,并将其一一存储。这将一直很困难,因为每次添加学生时都必须声明一个变量。记住所有变量的名称也是一项非常棘手的任务。但是,c使我们能够使用声明结构的数组,从而避免声明不同的结构变量;相反,我们可以创建一个包含所有存储不同实体信息的结构的集合。

结构数组

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

c array of structures

让我们看一个存储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:Learnfk
Enter Rollno:2
Enter Name:Toolfk
Enter Rollno:3
Enter Name:Poemfk
Enter Rollno:4
Enter Name:Chromefk
Enter Rollno:5
Enter Name:Nesfk

Student Information List:
Rollno:1, Name:Learnfk
Rollno:2, Name:Toolfk
Rollno:3, Name:Poemfk
Rollno:4, Name:Chromefk
Rollno:5, Name:Nesfk

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Java并发编程实战 -〔王宝令〕

雷蓓蓓的项目管理实战课 -〔雷蓓蓓〕

设计模式之美 -〔王争〕

小马哥讲Spring核心编程思想 -〔小马哥〕

Java业务开发常见错误100例 -〔朱晔〕

Selenium自动化测试实战 -〔郭宏志〕

分布式数据库30讲 -〔王磊〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)