Previous Lecture Lecture 9 Next Lecture

Lecture 9, Tue 07/31

Structs and Reference Variables

Structs

Defining a struct

struct Student { // Student is now a new defined type
	string name;
	int perm;
	double tuition;
}; // Syntactically, a ‘;’ is needed at the end of a struct definition.

Example

int main() {
	Student s1; // defining a variable containing the struct type Student
	s1.name = "Chris Gaucho";
	s1.perm = 1234567;
	s1.tuition = 3000.50;

	cout << "Name: " << s1.name << ", perm: " << s1.perm
		 << ", tuition: " << s1.tuition << endl;

	return 0;
}

Struct values as pointers

Student* s2 = &s1; // OK
s2.name = "Mr. E"; // ERROR! Why?
*s2.name = "Mr. E"; // Still contains an error!
(*s2).name = "Mr. E"; // OK. Pointer is dereferenced first, then name is accessed
s2->name = "Mr. E"; // OK. Same as (*s2).name

A larger example: courses with students

struct Student {
	string name;
	int perm;
	double tuition;
};
struct Course {
	string name;
	int enrolled;
	Student roster[100];
};

void printStudentInfo(Student s) {
	cout << "\tStudent Name: " << s.name << ", PERM: " <<
	s.perm << ", tuition: " << s.tuition << endl;
	return;
}

void printCourseInfo(Course c) {
	cout << "Course Name: " << c.name << ", Enrolled: " <<
	c.enrolled << endl;

	for (int i = 0; i < c.enrolled; i++) {
		printStudentInfo(c.roster[i]);
	}
	return;
}

int main() {

	Student s0;
	s0.name = "Chris Gaucho";
	s0.perm = 1234567;
	s0.tuition = 3000.50;

	Student s1;
	s1.name = "Jane Doe";
	s1.perm = 7654321;
	s1.tuition = 0;
	Student s2;
	s2.name = "John Doe";
	s2.perm = 5555555;
	s2.tuition = 10000;

	Course cs16;
	cs16.name = "CMPSC 16";
	cs16.enrolled = 3;
	cs16.roster[0] = s0;
	cs16.roster[1] = s1;
	cs16.roster[2] = s2;

	printCourseInfo(cs16);

	return 0;
}
double calculateTuitionAverage(Course c) {
	double totalTuition = 0;

	for (int i = 0; i < c.enrolled; i++) {
		totalTuition += c.roster[i].tuition;
	}

	return totalTuition / c.enrolled;
}

double calculateTuitionAverage(Course* c) {
	double totalTuition = 0;

	for (int i = 0; i < c->enrolled; i++) {
		totalTuition += c->roster[i].tuition;
	}

	return totalTuition / c->enrolled;
}

int main() {
// …
	cout << calculateTuitionAverage(cs16) << endl;
	cout << calculateTuitionAverage(&cs16) << endl;
}

Reference Variables

int x = 100;
int& y = x; // y references x

cout << x << ", " << y << endl;
x = 500;
cout << x << ", " << y << endl;
x = 200;
cout << x << ", " << y << endl;

Some differences between reference variables and pointers

Example (observe the addresses)

int a = 10;
int* p = &a;
int& r = a;

cout << "a = " << a << endl;
cout << "&a = " << &a << endl;
cout << "p = " << p << endl;
cout << "&p = " << &p << endl;
cout << "r = " << r << endl;
cout << "&r = " << &r << endl;

Memory Diagram