L20 - Unions, Function Pointers
L20 - Unions, Function Pointers
• Unions
• Function Pointers
Unions
union {
int myint;
char mychar;
char mystr[20];
} myun;
mystr
mychar
myint
member offset
myint 0
mychar 0
mystr 0
theplayer.thesport.footbstats.tds = 3;
Unions
Often used in implementing the polymorphism found in object-
oriented languages
Unions may
Unions may
be copied or assigned
have their address taken with &
have their members accessed
be passed as arguments to functions
be returned from functions
be initialized (but only the first member)
Notice similarity to
int ia[10];
int *ip;
ip = ia;
But what good is a function pointer?
Say you are writing a general purpose sorting function.
NAME
qsort - sort an array
ANSI_SYNOPSIS
#include <stdlib.h>
void qsort(void * base, size_t nmemb, size_t size,
int (* compar)(const void *, const void *) );
nmemb
base
size
qsort(3) qsort(3)
DESCRIPTION
qsort sorts an array (beginning at base) of nmemb objects.
size describes the size of each element of the array.
RETURNS
qsort does not return a result.
PORTABILITY
qsort is required by ANSI (without specifying the sorting
algorithm).
SOURCE
src/newlib/libc/stdlib/qsort.c
QSort Demo
#include <stdlib.h>
void qsort (
void * base,
size_t nmemb,
size_t size,
);
q
m.b = ‘q’;
\0 \0 \0 \0
Question