Definition and use of structure arrays

Preface

If you are not familiar with the use of structure variables, you can first read this article by the blogger [C Language] Structure Variable Definition, Initialization, and Usage

 

1. Define the structure array and initialize it


  
  
   
   
  1. //First declare the structure type
  2. struct students
  3. {
  4. char name[ 20];
  5. int age;
  6. };
  7. //Define the structure array and initialize it
  8. struct students stu[ 3]={ "Allen", 18, "Smith", 19, "Grace", 18};

In order to improve code readability, you can also use { } to group data during initialization (equivalent to the above code)

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

 

2. Reference structure array


  
  
   
   
  1. printf ( "name age\n\n" );
  2. //Loop output
  3. for( int i= 0;i< 3;i++)
  4. {
  5. printf( "%s %d\n\n",stu[i].name,stu[i].age);
  6. }

The result is as follows:

 

appendix

The complete test code is as follows:


  
  
   
   
  1. #include <stdio.h>
  2. # define NUM 3
  3. int main()
  4. {
  5. //Declare the structure type
  6. struct students
  7. {
  8. char name[ 20];
  9. int age;
  10. };
  11. //Initialize the structure array
  12. struct students stu[NUM]={ { "Allen", 18},{ "Smith", 19},{ "Grace", 18}};
  13. //Output
  14. printf ( "name age\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. }

The result is as follows:

Original link: https://blog.csdn.net/KinglakeINC/article/details/114242881

Guess you like

Origin blog.csdn.net/qq_38156743/article/details/131638946