Lecture 5: C Generics and Function Pointers¶
Function Pointers¶
1) Pointers are used to point to a variable of a particular data type.
Normally a pointer can only point to one type.
2) void *
is a type that can point to anything (generic pointer).
You can even have pointers to functions:
C | |
---|---|
1 |
|
fn
is a function that accepts two void *
pointers and returns an int
and is initially pointing to the function foo
.
(*fn)(x, y);
will then call the function
3) A function pointer is a variable storing the starting address of a function.
Function Pointers allow us to define higher-order functions, such as map, filter, and generic sort.
C | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Bash | |
---|---|
1 2 3 4 |
|
Generic Functions¶
Generic code reduces code duplication and means you can make improvements and fix bugs in one place rather than many.
C | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Too duplicated!!!
C | |
---|---|
1 2 3 4 5 6 7 |
|
Dereferencing void *
C | |
---|---|
1 2 3 4 5 6 |
|
C | |
---|---|
1 2 3 4 5 |
|
Why Case 1 is wrong while Case 2 is right?
- In case 1, we wanna dereference a
void*
, if succeed, we get a type calledvoid
, which is of no sense. - In case 2, we wanna dereference a
void**
, if succeed, we get avoid*
, which is ok as a generic type.
Supplementary
To dereference a pointer, we must know the number of bytes to access from memory at compile time.
Generics employ generic pointers and therefore cannot use the dereference operator!
Generic Memory Copying¶
To access some number of bytes in memory with a generic-typed void *
pointer, we use two generics in the string standard library:
C | |
---|---|
1 |
|
Copy n bytes from memory area src
to memory area dest
.
C | |
---|---|
1 |
|
Also: Copy n bytes from memory area src
to memory area dest
.
C | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 |
|
Pointer Arithmetic in Generics¶
Use the swap function to swap the first and last elements in an array:
C | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
What we pursue:
C | |
---|---|
1 2 3 4 5 6 |
|
The problem equals to: How to present a pointer towards the last element in this 1-D array?
C | |
---|---|
1 |
|
We must write (char*)
explicitly!!!
Why
Pointer arithmetic in generics must be bytewise!
- Cast
void *
pointer tochar *
. - Pointer arithmetic is then effectively byte-wise!