13.07.2015 Views

struct 1 - Tenouk C & C++

struct 1 - Tenouk C & C++

struct 1 - Tenouk C & C++

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

strcpy(Player1.Country, Player2.Country);will copy the country (value) of Player2 as the country of Player1. Additionally, while Player2.Countryis equal to the string “Kenya”, Player2.Country[3] is equal to the character ‘y’. We can always writean array of players like the following.<strong>struct</strong> Participant Player[2];This will create an array called Player[ ] with only 2 slots, where each slot is a <strong>struct</strong>ure of type<strong>struct</strong> Participant. See the following Figure that try to depict an array of <strong>struct</strong>ure.To read in the name for the player in slot 0, the statement will look like this:// scanf("%s, &Player[0].Name);scanf_s("%s, &Player[0].Name, 20);The & is optional here because as you have learned previously, array names are actualaddresses anyway. We can also create a <strong>struct</strong>ure based on other <strong>struct</strong>ures. Consider thethe following code example.<strong>struct</strong> Team // defining a new <strong>struct</strong>ure{<strong>struct</strong> Participant Captain; // <strong>struct</strong> Team contains a <strong>struct</strong>ureint Wins;int Losses;<strong>struct</strong> Participant Player[2]; // <strong>struct</strong> Team has an array of <strong>struct</strong>ures};// defining and initializing a variable<strong>struct</strong> Team SweetThings ={{"Jasmine", "Cambodia", 3.5, 22},5,2,{{"Michael", "Mexico", 5.2, 20},{"Leonard", "Germany", 4.0, 24}}};// just defining a variable<strong>struct</strong> Team RowdyBabies;// need the outer bracesIn the following Figure, you can see what the variable SweetThings looks like, a <strong>struct</strong>ure of <strong>struct</strong>ures.If we want to copy the contents of SweetThings to RowdyBabies, all we need to do is:RowdyBabies = SweetThings;However, for the sake of obtaining experience in handling <strong>struct</strong>ures, let us do the same thing thelong way.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!