Pointer to Array of Structure
- Pointer Variable can also Store the Address of the Structure Variable.
- Pointer to Array of Structure stores the Base address of the Structure array.
- 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} };
- Pointer Is Declared and initialized as ---
struct Cricket *ptr = match
- Here the address of match[0] is stored in pointer Variable ptr.
Program Main Function :
Output :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++; } }
You can Write above Program :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
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++; } }
2 Comments:
There is a small mistake in the if statement given in for loop. The statements in if condition both are same even the condition is true or false.
@ Rajesh Patnal
Thanks Rajesh I have Corrected it , But i just want to show that how members of the structure are used in the if statement for comparison... but still I appreciate you for your valuable suggestion.
Post a Comment
Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email