nested structures

Allows structures (i.e. one type of user defined data type) to be used within other structures.

 

#include <iostream>
using namespace std;

//declare a structure (user defined data type) called rider, with 2 objects called: smith, marquez
struct team {
	string team;
	int pos;
} ;

struct rider {
	int age ;
	string name ;
	team teamName ;
} ninth ;

//function prototype called details, declaring a variable called anything of the data type rider
void details (rider *someLabel);

int main () {

	rider *ptr = &ninth; //define pointer to 'ninth' object, of data type: rider

	ptr->age = 21 ; //set age variable (of data type: rider) for ninth object
	ptr->name = "Smith" ; //set name variable for ninth object
	ptr->teamName = {"test", 9} ; //set teamName for ninth object

	ptr->teamName.team = "Monster Yamaha Tech 3" ; //reset team variable within teamName struct

	details(ptr) ; //display details

	rider first = {17, "Marquez", {"Honda", 1} } ; //initialise 'first' object

	ptr = &first ; //reset pointer to point to first object

	details(ptr) ;

	return 0;
}

void details (rider *ptr) {
	cout << ptr->name << " rides a " << ptr->teamName.team ;
	cout << " and finished in position " << ptr->teamName.pos << endl ;
}

Compile & Run:

Smith rides a Monster Yamaha Tech 3 and finished in position 9
Marquez rides a Honda and finished in position 1

Leave a Reply