结构体数组的定义与使用

前言

如果对结构体变量的使用不太熟悉,可以先看看博主的这篇文章【C语言】结构体变量定义、初始化、使用

一、定义结构体数组,并初始化


  
  
   
   
  1. //首先声明结构体类型
  2. struct students
  3. {
  4. char name[ 20];
  5. int age;
  6. };
  7. //定义结构体数组,并初始化
  8. struct students stu[ 3]={ "Allen", 18, "Smith", 19, "Grace", 18};

为了提高代码可读性,在初始化时,也可以用 { } 将数据分组(与上述代码等价)

struct students stu[NUM]={
    
    {
    
    "Allen",18},{
    
    "Smith",19},{
    
    "Grace",18}};
  
  
   
   

 

二、引用结构体数组


  
  
   
   
  1. printf( "姓名 年龄\n\n");
  2. //循环输出
  3. for( int i= 0;i< 3;i++)
  4. {
  5. printf( "%s %d\n\n",stu[i].name,stu[i].age);
  6. }

结果如下:

附录

完整测试代码如下:


  
  
   
   
  1. #include <stdio.h>
  2. #define NUM 3
  3. int main()
  4. {
  5. //声明结构体类型
  6. struct students
  7. {
  8. char name[ 20];
  9. int age;
  10. };
  11. //初始化结构体数组
  12. struct students stu[NUM]={ { "Allen", 18},{ "Smith", 19},{ "Grace", 18}};
  13. //输出
  14. printf( "姓名 年龄\n\n");
  15. for( int i= 0;i<NUM;i++)
  16. {
  17. printf( "%s %d\n\n",stu[i].name,stu[i].age);
  18. }
  19. return 0;
  20. }

结果如下:

原文链接:https://blog.csdn.net/KinglakeINC/article/details/114242881

猜你喜欢

转载自blog.csdn.net/qq_38156743/article/details/131638946