Create your own types typedef define N 3

  • Slides: 8
Download presentation
Create your own types: typedef #define N 3 typedef double scalar; vector[N]; /* note

Create your own types: typedef #define N 3 typedef double scalar; vector[N]; /* note defs outside fns */ 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

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; }; struct card_struct { int pips; char suit; } c 1, c 2; 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

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

Structures – initialize #include <stdio. h> struct { char long }; address_struct *street; *city_and_state;

Structures – initialize #include <stdio. h> struct { char long }; address_struct *street; *city_and_state; 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

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( “%dn”, *a ); }

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

Valid. #include <stdio. h> int *function_3(); void main() { int *a; a = function_3();

Valid. #include <stdio. h> int *function_3(); void main() { int *a; a = function_3(); printf( “%dn”, *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,

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( "%dn", sum ); free( numbers ); }