Previous Lecture lect03 Next Lecture

Relevant topics in the textbook:

Data Structures and Other Objects Using C++ Chapter 4.1

Structs - refreshment

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

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 Stack

Example

#include <iostream>

using namespace std;

int doubleValue(int x) {
	return 2 * x;
}

int quadrupleValue(int x) {
	return doubleValue(x) + doubleValue(x); 
}

int main() {
	int result = quadrupleValue(4);
	cout << result << endl;
	return 0;
}
|                       |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int doubleValue(4)    |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int doubleValue(4)    |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int main()            |
|_______________________|

Stack vs heap: