0. Recap of arrays and pointers int arr[3] = {1, 2, 3}; int *p, *q; p = arr; q = p; q++; //what are the different ways to access the 3rd element of the array? printf("%d", arr[2]); //*(arr+2) //p[2] //*(p+2) //q[1] //*(q+1) int **r; r = &p; //what is (*r)+1 (*r)[2] = 1; //what is arr[2]? 1 There's no bound checking for C arrays! int n; n = arr[3]? //what is n?? arr[3] = 10 //what happens? segfaults? 1. Multi-dimentional arrays int matrix[3][2] = { {1, 2}, {3,4}, {5,6}}; int *p = &matrix[0][0]; //equivalent to p = matrix[0] for (i = 0; i < 3; i ++) { for (j = 0; j < 2; j++) { sum += matrix[i][j]; } } for (i = 0; i < 3 * 2; i++) { sum += p[i]; or sum += *(p+i); } 2. 2D array vs. array of pointers int m[2][3] = { {1, 2, 3}, {4, 5,6}}; int *n[2]; m:|_|_|_|_|_|_|_| n: |_|_| n[0] = &m[0][0]; //equivalent to n[0] = m[0] n[1] = &m[1][0]; //equivalent to n[1] = m[1] what is n[0][1]? //2 m[0][1]? // same as n[0][1] What is n[1][1]? //2 What is m[1][1]? //same as n[1][1] What about n[0][5]? //6 n[1] = m[0]; what is n[1][1] now? //2 n[1][1]++; //what are all elements of m? // 1 3 3 4 5 6 n[1][3]++; //what are all elements of m? // 1 3 3 5 5 6 3. structure enum Year { Freshman, Sophomore, Junior, Senior }; // alternatively, typedef enum {Freshman, Sophomore, Junior, Senior} Year; Year level; struct student { int id; enum Year level; } //Java has no structs, so above is similar to a java class with only public class variables and no associated class methods struct student s; struct student *sp; s.id = 1; s.level = Freshman; sp = &s; sp->id = 3; //what is s.id? //what is s.level? To make things simpler, typedef struct { int id; Year level; } student; 4. A linked list typedef struct { int value; struct node *next; } node; //insert n to before the current head of the linked list void push(node **head, node *n) { n->next = *head; *head = n; } //detach the first node of the linked list, // return the detached node node * pop(node **head) { node *n = *head; if (n) { *head = n->next; } return n; } void main() { node *head; // wring, missing head = NULL node n1; n1.value = 1; node n2; n2.value = 2; push(&head, &n1); push(&head, &n2); node *np = push(&head); } 5. malloc Global variables are allocated space before program execution. Local variables are allocated space at the entrace of a function/block and deallocated space upon exit. Allocate space dynamically on the heap (and have it persist across functions/blocks)? malloc - allocate storage of a give size free - de-allocate previously malloc-ed storage #include node * newNode(int value) { node *n = (node *)malloc(sizeof(node)); n->value = value; return n; } void main() { node *head; // wrong, missing head = NULL for (int i = 0; i < 1000; i++) { node *n = newNode(i); push(&head, n); } //delete all nodes in linked list node *n; do { n = pop(&head); if (n) { free(n); } } while (n); }