Presentation is loading. Please wait.

Presentation is loading. Please wait.

Create your own types: typedef #define N 3 typedef double scalar; /* note defs outside fns */ typedef scalar vector[N]; typedef scalar matrix[N][N]; /*

Similar presentations


Presentation on theme: "Create your own types: typedef #define N 3 typedef double scalar; /* note defs outside fns */ typedef scalar vector[N]; typedef scalar matrix[N][N]; /*"— Presentation transcript:

1 Create your own types: typedef #define N 3 typedef double scalar; /* note defs outside fns */ typedef scalar vector[N]; typedef scalar matrix[N][N]; /* last def. could also be typedef vector matrix[N]; */ void add( vector x, vector y, vector z ) { int i; for( i = 0; i < N; i++ ) { x[i] = y[i] + z[i]; }

2 Structures struct card_struct { int pips; char suit; }; typedef struct card_struct card; The structure mechanism allows us to aggregate variables of different types Your struct definition generally goes outside all functions struct card_struct { int pips; char suit; } c1, c2; typedef struct card_struct card; void some_function() { struct card_struct a; card b; /* a, b have same types */ b.pips = 3; }

3 Structures – accessing via pointer struct card_struct { int pips; char suit; }; typedef struct card_struct card; void main() { card a; set_card( &a ); } void set_card( card *c ) { c->pips = 3; c->suit = ‘A’; }

4 Structures – initialize #include struct address_struct { char *street; char *city_and_state; long zip_code; }; typedef struct address_struct address; void main() { address a = { "1449 Crosby Drive", "Fort Washington, PA", 19034 }; }

5 Unions union int_or_float { int i; float f; }; union int_or_float a; /* need to keep track of, on own, which type is held */ /* a.i always an int, a.f always a float */

6 Fishy. void main() { int *a; a = function_3(); printf( “%d\n”, *a ); } int *function_3() { int b; b = 3; return &b; }

7 Valid. #include int *function_3(); void main() { int *a; a = function_3(); printf( “%d\n”, *a ); free( a ); } int *function_3() { int *b; b = (int *) malloc( sizeof( int )); /* NULL? */ *b = 3; return b; }

8 Getting an array of numbers #include void main() { int *numbers, size, i, sum = 0; printf( "How many numbers? " ); scanf( "%d", &size ); numbers = malloc( size * sizeof( int )); for( i = 0; i < size; i++ ) { scanf( "%d", &numbers[i] ); } for( i = 0; i < size; i++ ) { sum += numbers[i]; } printf( "%d\n", sum ); free( numbers ); }


Download ppt "Create your own types: typedef #define N 3 typedef double scalar; /* note defs outside fns */ typedef scalar vector[N]; typedef scalar matrix[N][N]; /*"

Similar presentations


Ads by Google