Revision as of 05:08, 28 February 2012 by Jribeir (Talk | contribs)

Lecture 15 - John Ribeiro

  1. ifndef
  1. define SOMETHING
  1. 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;

}

- Actually changes values in heap memory

VS.

void Vector_double2 ( Vector v ) {

 v.x *= 2;
 v.y *= 2;
 v.z *= 2;

}

- Changes the values but does changes are lost when function is returned

- A single function should contain one idea - A function should b4e no longer than ~30 lines

typedef struct {

 int age;
 char * name;

} Person;

Person * Person_construct ( int a, char * n ) {

 Person * p;
 p = malloc ( sizeof ( Person ) );
 p -> age = a;
 p -> name = malloc ( sizeof (char) * ( strnlen (n) + 1 ) );
 strcpy ( p -> name, n );
 return p;

}

void Person_destruct ( Person * p ) {

 free ( p->name);
 free (p);

}

- Do no use assertion - kills the program when a condition is not met

assert ( x != 0 )

/* If x is 0, the program is killed */


--

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

Alumni Liaison

ECE462 Survivor

Seraj Dosenbach