Defining our own datatypes, continued
Let's consider another example -
the starting (home) and ending (destination) bustops from the
CITS2002 1st project of 2015.
We starting with some of its definitions:
// GLOBAL CONSTANTS, BEST DEFINED ONCE NEAR THE TOP OF FILE
#define MAX_FIELD_LEN 100
#define MAX_STOPS_NEAR_ANYWHERE 200 // in Transperth: 184
....
// 2-D ARRAY OF VIABLE STOPS FOR COMMENCEMENT OF JOURNEY
char viable_home_stopid [MAX_STOPS_NEAR_ANYWHERE][MAX_FIELD_LEN];
char viable_home_name [MAX_STOPS_NEAR_ANYWHERE][MAX_FIELD_LEN];
int viable_home_metres [MAX_STOPS_NEAR_ANYWHERE];
int n_viable_homes = 0;
// 2-D ARRAY OF VIABLE STOPS FOR END OF JOURNEY
char viable_dest_stopid [MAX_STOPS_NEAR_ANYWHERE][MAX_FIELD_LEN];
char viable_dest_name [MAX_STOPS_NEAR_ANYWHERE][MAX_FIELD_LEN];
int viable_dest_metres [MAX_STOPS_NEAR_ANYWHERE];
int n_viable_dests = 0;
|
(After a post-project workshop)
we later modified the 2-dimensional arrays to use
dynamically-allocated memory and 'pointers-to-pointers':
// 2-D ARRAY OF VIABLE STOPS FOR COMMENCEMENT OF JOURNEY
char **viable_home_stopid = NULL;
char **viable_home_name = NULL;
int *viable_home_metres = NULL;
int n_viable_homes = 0;
// 2-D ARRAY OF VIABLE STOPS FOR END OF JOURNEY
char **viable_dest_stopid = NULL;
char **viable_dest_name = NULL;
int *viable_dest_metres = NULL;
int n_viable_dests = 0;
|
We can now gather the (many) related global variables into a single structure,
and use typedef to define our own datatype:
// A NEW DATATYPE TO STORE 1 VIABLE STOP
typedef struct {
char *stopid;
char *name;
int metres;
} VIABLE;
// A VECTOR FOR EACH OF THE VIABLE home AND dest STOPS
VIABLE *home_stops = NULL;
VIABLE *dest_stops = NULL;
int n_home_stops = 0;
int n_dest_stops = 0;
|
CITS2002 Systems Programming, Lecture 16, p4, 19th September 2023.
|