Charlotte Curtis March 4, 2024
typedef
Textbook Sections 9.1, 9.2
Time t; Time *pt = &t; t.hour = 5; t.minute = 0; cout << pt->hour << ':' << pt->minute << endl;
Textbook Sections 9.2, 6.1
new
To create a variable on the heap, use the new operator:
int x = 0; // x is a named memory location on the stack int *ptr; // memory for pointer is on the stack ptr = new int; // what it points at is on the heap
ptr
ptr = &x;
int
struct
Applicant *a = new Applicant; // Allocates all 19 fields on the heap
strcpy(a->name, "Aaron Grimm"); cout << a->name << endl;
delete
Applicant
delete a;
Caution: this recycles the memory, but does not remove the pointer! Good idea to reset the pointer to NULL after a delete
NULL
Risks:
int n; cin >> n; int *arr = new int[n];
n
arr[0] = 5; a_func_that_uses_an_array(arr, n);
delete [] arr;
Pub trivia style! Answers are now posted.
Q5:
int x = 5; int *p1; int *p2 = &x;
Q9:
int nums[8], n; cin >> n; for (int i = 0; i < n; i++) { cin >> nums[i]; }