C pointer to array of structure

Pointer to Array of Structure

  1. Pointer Variable can also Store the Address of the Structure Variable.
  2. Pointer to Array of Structure stores the Base address of the Structure array.
  3. Suppose
struct Cricket
{
    char team1[20];
    char team2[20];
    char ground[18];
    int result;
}match[4] = {
              {"IND","AUS","PUNE",1},
              {"IND","PAK","NAGPUR",1},
              {"IND","NZ","MUMBAI",0},
              {"IND","SA","DELHI",1}
            };
  1. Pointer Is Declared and initialized as —
struct Cricket *ptr = match
  1. Here the address of match[0] is stored in pointer Variable ptr.

Live Example Program :

void main() 
{
struct Cricket *ptr = match;   // By default match[0]
for(i=0;i<4;i++) 
    {
    printf("\nMatch : %d",i+1);
    printf("\n%s Vs %s",ptr->team1,ptr->team2);
    printf("\nPlace : %s",ptr->ground);
    if(match[i].result == 1)
        printf("nWinner : %s",ptr->team1);
    else
        printf("nWinner : %s",ptr->team1);
    printf("\n");
    // Move Pointer to next structure element
    ptr++;
    }
}

Output :

Match : 1
IND Vs AUS
Place : PUNE
Winner : IND
Match : 2
IND Vs PAK
Place : NAGPUR
Winner : IND
Match : 3
IND Vs NZ
Place : MUMBAI
Winner : NZ
Match : 4
IND Vs SA
Place : DELHI
Winner : IND

You can Write above Program :

void main() 
{
struct Cricket *ptr = match;   // By default match[0]
    for(i=0;i<4;i++)
    {
    printf("\nMatch : %d",i+1);
    printf("\n%s Vs %s",ptr->team1,ptr->team2);
    printf("\nPlace : %s",ptr->ground);
    printf("\nWinner : %s",ptr->team1);
    printf("\n");
    // Move Pointer to next structure element
    ptr++;
    }
}