LECTURE NOTES_2/23_Kailu Song
(WHY CONSTRUCTOR? a single place where all attributes are assigned) (malloc in constructor = copy+assign+destructor)
typed of struct {
char *name;(if structure don't have pointer can write pointer Person P3 = P1; if copy attribute by attribute will get shallow copy) int year; int month; int data;
} Person; Person Person_construct(char *n, int y, int m, int d) {
Person P; P.name = malloc(sizeof(char)*strlen(n)+1); (check if P.name is = NULL) strepy(P.name,n); P.year = y; P.month = m; P.date = d; return P;
} void Person_destruct(Person P) {
free(P.name);
} Person Person_coty(Person P) {
return Person_construct(P.name,P.year,P.month,P.data); (inside the construct function,there is a malloc, so create another heap memory)
} Person Person_assign(Person P1, Person P2) {
Person_destruct(P1); return Person_copy (P2);
} Person P1 = Person_construct("Amy",1980,10,21); Person P2 = Person_construct("Jennifer",1981,2,5); Person P3 = Person_copy(P1); P3 = Person_assign(P3,P2);(if change this line to P3 = Person_copy(P2),P2 will become leak memory become there are two mallocs) Person_destruct(P1); Person_destruct(P2); Person_destruct(P3);
HINT FOR IPA1-3: Maze_traverse(Maze xmz, int from, int *forward) {
if (canMove(east)) { forward = 1; from = west; Maze_traverse(...east); book leaping;(dead end) } if (canMove(south)) { forward = 1; from = west; Maze_traverse(...south); book leaping;(dead end) } if (canMove(west)) { forward = 1; from = west; Maze_traverse(...west); book leaping;(dead end) } if (canMove(north)) { forward = 1; from = west; Maze_traverse(...north); book leaping;(dead end) }
}
canMove {
CHECK whether it is a brick; CHECK where you come from; CHECK whether *forward = 1;
}