Line 1: | Line 1: | ||
+ | Lecture 15 - John Ribeiro | ||
+ | |||
+ | #ifndef | ||
+ | |||
+ | #define SOMETHING | ||
+ | |||
+ | #endif | ||
+ | |||
+ | typedef struct | ||
+ | { | ||
+ | int x; | ||
+ | int y; | ||
+ | int z; | ||
+ | } Vector; | ||
+ | |||
+ | Vector * Vector_construct ( int a, int b, int c ) | ||
+ | { | ||
+ | Vector * v; | ||
+ | v = malloc ( sizeof ( Vector ) ) ; | ||
+ | v -> x = a; | ||
+ | v -> y = b; | ||
+ | v -> z = c; | ||
+ | return v; | ||
+ | } | ||
+ | |||
+ | void Vector_destruct ( Vecotr *v) | ||
+ | { | ||
+ | free ( v ); | ||
+ | } | ||
+ | |||
+ | Advantages of Using Pointers | ||
+ | |||
+ | void Vector_double ( Vector *v ) | ||
+ | { | ||
+ | v-> x *= 2; | ||
+ | v-> y *= 2; | ||
+ | v-> z *= 2; | ||
+ | } | ||
+ | |||
+ | |||
+ | -- | ||
+ | |||
On IPA 1-2 | On IPA 1-2 | ||
Revision as of 05:04, 28 February 2012
Lecture 15 - John Ribeiro
- ifndef
- define SOMETHING
- endif
typedef struct {
int x; int y; int z;
} Vector;
Vector * Vector_construct ( int a, int b, int c ) {
Vector * v; v = malloc ( sizeof ( Vector ) ) ; v -> x = a; v -> y = b; v -> z = c; return v;
}
void Vector_destruct ( Vecotr *v) {
free ( v );
}
Advantages of Using Pointers
void Vector_double ( Vector *v ) {
v-> x *= 2; v-> y *= 2; v-> z *= 2;
}
--
On IPA 1-2
If you use #ifndef, you must use #define otherwise, you defeat the purpose of #ifndef
February 28
Each func should only do ONE thing Points will be taken if your program has “gigantic” functions (i.e. everything is in main)
If you malloc in your constructor, you must create a destructor.
Example Time!
void Vector_double(Vector v) {
v->x *= 2; v->y *= 2; v->z *= 2;
}
void Vector_double2(Vector v) {
v.x *= 2; v.y *= 2; v.z *= 2;
}
In the first case, the attributes are pointers. In the second case, the attributes are copy. In the copy, nothing happens after you leave the function. As a pointer, you can change the attributes separately. Also, if you have a large complex program it will also take very long to run the program because it must copy all of the attributes in the second case.
The constructor-destructor is symmetric. Meaning: malloc first, free last.
Controversy of Assert
Don’t kill the program. Handle problems. The idea of programming is changing. It is different from 20-40 years ago. Bottom line: do not use assert();
Don’t cheat on your IPA. If you spent so much time trying to change your program, why don’t you use the time to make your own program. Plagiarism is not acceptable.
Exam Review
Makefiles
Recursion
Search
File I/O (text & binary)
Memory (malloc/free)
Structures (with/without pointers)
Pointers
Stack/Heap
Functions
2-D Arrays
Strings
Some code will be given; you must follow this code. Open notes: you can use anything on paper or your programs. You will not have time to studying during the exam. Make sure you know every exercise and programming assignment.
Feb 28 Notes by T.Gao