V Lecture 10 — the struct type
V midterm on Feb 8
* will include the material from this week
* will not include the material from next week
V clint.py
* wget http://courses.cs.washington.edu/courses/cse374/16wi/hws/clint.py
* chmod +x clint.py
* ./clint.py SOURCE_FILE
V gdb
* -g option for gcc compiles with debugging information
* gdb EXECUTABLE to start debugger
* run ARGS to run the program
V backtrace to see the chain of function calls that lead to this point
* frame N to switch to function call N (0 is the current call)
* list to see the surrounding code
* print VAR_NAME to see the value of a variable
* quit to end the debugger (it may ask about terminating the running program)
* deeper look in a future lecture
V structs
V motivation: consider representing a 2D point or a linked list
* we need some way to group multiple pieces of data together
* a C struct is exactly this: pieces of data bundled together
V point example
* struct point {
int x;
int y;
};

struct point p;
p.x = 2;
p.y = 2;
V struct point makepoint(int x, int y) {
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}
struct point pt = makepoint(2, 2);
* temp is copied when it is returned
V exercise: write the definition for a string struct that contains a string and its length
* struct string {
char *str;
int len;
};
V we can avoid putting struct everywhere by using typedef
* typedef just makes an alias for an existing type
* typedef struct point Point;
Point p;
* can also incorporate it into the definition:
typedef struct point {
int x;
int y;
} Point;
V exercise: write a function add_point that takes two points and returns their sum
V Point add_point(Point p1, Point p2) {
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
* p1 copied on the way in and on the way out
V A struct can contain other structs
* typedef struct rect {
Point p1;
Point p2;
} Rect;
V You can have arrays of structs
* Point points[10];
V and, of course, pointers to structs
* Point *pp = &p;
V need to deference to access memebers
V void add_point(Point *p1, Point *p2) {
(*p1).x += (*p2).x;
(*p1).y += (*p2).y;
}
* need ( ) because . has higher precedence than *
* this is very common, so C gives us nicer syntax
* void add_point(Point *p1, Point *p2) {
p1->x += p2->x;
p1->y += p2->y;
}
V exercise: define a struct for a bank account that includes an account number, first name, last name, and balance. Then write a function update_balance that takes a bank account and an integer indicating the change in balance
* typedef struct account {
int account_number;
char *first_name;
char *last_name;
float balance;
} Account ;

void update_balance(Account *acc, int delta) {
acc->balance += delta; // may cause balance to go negative
}