C - Making an array of structures

Introduction

A structure array is declared like this:

struct scores { 
       char name[32]; 
       int score; 
}; 
   
struct scores player[4]; 

This statement declares an array of scores structures.

The array is named player, and it contains four structure variables as its elements.

The structures in the array are accessed by using a combination of array and structure notation. For example:

player[2].name 

The variable accesses the name member in the third element in the player structure array.

Demo

#include <stdio.h> 

int main() /*from w ww  .j  a v a 2  s.  com*/
{ 
   struct scores 
   { 
       char name[32]; 
       int score; 
   }; 
   struct scores player[4]; 
   int x; 

   for(x=0;x<4;x++) 
   { 
       printf("Enter player %d: ",x+1); 
       scanf("%s",player[x].name); 
       printf("Enter their score: "); 
       scanf("%d",&player[x].score); 
   } 

   puts("Player Info"); 
   printf("#\tName\tScore\n"); 
   for(x=0;x<4;x++) 
   { 
       printf("%d\t%s\t%5d\n", 
           x+1,player[x].name,player[x].score); 
   } 
   return(0); 
}

Result

Related Topic