🛖

Unions, Function Pointers

TypeQuiz 4 Material

Unions

Union is a user-defined datatype. It is a collection of variables of different data types in the same memory location.

union {
	int myint;
	char mychar;
	char mystr[20];
} myun;

Looks like a struct, and the access is the same as a struct The difference is that all the members have an offset of zero

Unions may:

Unions may not:

Unions in memory with example above

union {
	int myint;
	char mychar;
	char mystr[20];
} myun;

&myun.myint == &myun.mychar == &myun.mystr[0]
sizeof(myun) == sizeof("Largest member")

Uses for Union

raison d'être

Union is often used in implementing polymorphism found in OOP

Store information about aletes

struct player {
	char name[20];
	char jerseynum[4];
	char team[20];
	int player_type;
	union sport {
		struct football {...} footbstats;
		struct baseball {...} basebstats;
		struct baseketball {...} baskbstats;
		} thesport;
} theplayer;
theplayer.thesport.footbstats.tds = 3;

Function Pointers

int fi(void) 
/* Function that returns an int*/
int *fpi(void) 
/* Function that returns a pointer to an int*/
int (*pfi) (void) 
/* pfi is a pointer to a function returning int*/
pfi = fi; 
/*Legal assigment*/
/*Funciton name without () is the memory address*/
pfi = fi(); 
/*NO! BAD!*/
/*fi() is a pointer to an int*/

QSort()

Question