CSC209H Worksheet: structs
1. Here is the beginning of a program involving structs. You will need to fill in missing bits. If you can work with a partner with a machine and actually compile your program at each step, do that. If not, work on paper.
#define MAX_AREA_SIZE 16
#include
#include
#include
struct faculty {
char *name;
char area[MAX_AREA_SIZE];
int num_students;
};
int main() {
// Declare a struct faculty called p1.
// Initialize p1 to represent Professor Roger Grosse, whose research area
// is ML (Machine Learning). He is supervising 11 graduate students.
2. Here we have added a declaration for a pointer to a struct faculty. Allocate space for the struct on the heap and have p2_pt point to that memory.
Error-checking: Look at the man page for malloc to see what it returns if it is unable to allocate memory. Now add code to check if the memory allocation for p2_pt was successful, and if it failed, exit the program with a non-zero exit status.
struct faculty *p2_pt;
// Set the values of *p2_pt to represent Professor Sheila McIlraith. Her research area
// is KR (Knowledge Representation). She is supervising 11 graduate students.
CSC209H Worksheet: structs
3. Write a function add_grad_student that increments the num_students count for the faculty passed as the function¡¯s argument. Think carefully about what the type of the function parameter should be.
4. Show how to make calls to add_grad_student using p1 and p2_pt.
5. Suppose we have the following function declaration.
void f(struct faculty p) { // Body hidden }
Now suppose we call it from main using f(p1). Draw the memory diagram of the program immediately after f
is called, but before it starts executing. For extra practice, include p2 pt and related memory in your diagram.
6. Something to think carefully about: can the body of f affect the local p1 of main? In other words, after f(p1) exits, can any data associated with p1 have changed?
7. On a new sheet of paper, repeat the previous two questions when you call f(*p2 pt) instead.