80 likes | 128 Views
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;
E N D
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]; } }
Structures • 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; }; typedef struct card_struct card; 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; }
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’; }
Structures – initialize #include <stdio.h> 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 }; }
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 */
Fishy. void main() { int *a; a = function_3(); printf( “%d\n”, *a ); } int *function_3() { int b; b = 3; return &b; }
Valid. #include <stdio.h> 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; }
Getting an array of numbers #include <stdio.h> 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 ); }