Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C: Function Pointers for Overriding Functions & Generic Arrays, Lecture notes of Printing

An overview of function pointers in C programming, focusing on their usage for overriding functions and handling generic arrays. the concept of function pointers, their syntax, and examples of their implementation. It also discusses the use of function pointers in the qsort algorithm and provides examples of sorting arrays using different comparison functions.

What you will learn

  • What is the difference between a function pointer and a regular function call?
  • How do function pointers work in C?
  • How can function pointers be used to sort arrays in C?

Typology: Lecture notes

2021/2022

Uploaded on 09/12/2022

ekaashaah
ekaashaah 🇺🇸

4.4

(40)

274 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1"
Pointers to Functions
Based on slides from K. N. King and Dianna Xu
Bryn Mawr College
CS246 Programming Paradigm
Pointers to Functions
C doesnt require that pointers point only to data;
its also possible to have pointers to functions.
Function pointers point to memory addresses where
functions are stored.
oint (*fp) (void);
oA function pointer determines the prototype of a
function, but not its implementation.
oAny function of the identical prototype can be
assigned to the function pointer.
oA function without its argument lists becomes its
own pointer
oFunction pointers do not need & or *
Function Pointer: Example
#include <stdio.h>
int main() {
int i = 1;
int (*fp) (const char *, ...) = printf;
fp("i == %d\n", i);
(*fp)("i == %d\n", i);
return 0;
}
Notice no need for &printf or (*fp)
But I like to stick with (*fp)
Overriding Functions
Also known as late-binding, this is emulated in C with
function pointers.
Together with generic pointers (void *), one can have
typeless parameters and functions.
void fd (void *base, size_t n, size_t size){
double *p = base;
for (p = base; p < (double*) (base+(n*size)); p++) ;
}
int main() {
double a[5] = {0, 1, 2, 3, 4};
if (type == DOUBLE) {
void (*f) (void *, size_t, size_t) = fd;
(*f)(a, 5, sizeof(double));
}
}
Printing of Generic Arrays
typedef struct {
double x;
double y;
} Point;
int main() {
double a[5] = {0, 1, 2, 3, 4};
int b[5] = {5, 6, 7, 8, 9};
Point ps[2] = {{0.5, 0.5}, {1.5, 2.5}};
gp(a, 5, sizeof(double));
gp(b, 5, sizeof(int));
gp(ps, 2, sizeof(Point));
}
Printing of Generic Arrays
void gp (void *b, size_t n, size_t size){
char *p;
for (p=b; p <(char*)(b+(n*size)); p+=size){
switch (size) {
case sizeof(double):
printf("%.2f ", *(double*)p);
break;
case sizeof(int):
printf("%d ", *(int*)p);
break;
case sizeof(Point):
printf("x = %.2f ", ((Point *)p)->x);
printf("y = %.2f ", ((Point *)p)->y);
break;
}}
printf("\n"); }
pf3
pf4
pf5

Partial preview of the text

Download C: Function Pointers for Overriding Functions & Generic Arrays and more Lecture notes Printing in PDF only on Docsity!

Pointers to Functions

Based on slides from K. N. King and Dianna Xu Bryn Mawr College CS246 Programming Paradigm

Pointers to Functions

  • C doesn’t require that pointers point only to data; it’s also possible to have pointers to functions.
  • Function pointers point to memory addresses where functions are stored. o int (fp) (void);* o A function pointer determines the prototype of a function, but not its implementation. o Any function of the identical prototype can be assigned to the function pointer. o A function without its argument lists becomes its own pointer o Function pointers do not need & or *****

Function Pointer: Example

#include <stdio.h> int main() { int i = 1; int (fp) (const char , ...) = printf; fp("i == %d\n", i); (fp)("i == %d\n", i); return 0; }*

  • Notice no need for &printf or (fp)*
  • But I like to stick with (fp)*

Overriding Functions

  • Also known as late-binding, this is emulated in C with function pointers.
  • Together with generic pointers ( *void *** ), one can have typeless parameters and functions. void fd (void base, size_t n, size_t size){ double for (p p= base;= base; p < (double) (base+(nsize)); p++) ; } int main() { double if (type a[5] == =DOUBLE) {0, 1, {2, 3, 4}; void (f) (void , size_t, size_t) = fd; }^ (f)(a,^ 5,^ sizeof(double)); }

Printing of Generic Arrays

typedef struct { double x; double y; } Point; int main() { double a[5] = {0, 1, 2, 3, 4}; int b[5] = {5, 6, 7, 8, 9}; Point ps[2] = {{0.5, 0.5}, {1.5, 2.5}}; gp(a, 5, sizeof(double)); gp(b, 5, sizeof(int)); gp(ps, 2, sizeof(Point)); }

Printing of Generic Arrays

void char gp p;(void b, size_t n, size_t size){ for (p=b; p <(char)(b+(nsize)); p+=size){ switch case sizeof(double): (size) { printf("%.2f ", (double)p); case^ **break; sizeof(int): printf("%d ", (int)p); break; case printf("x sizeof(Point): = %.2f ", ((Point )p)->x); printf("y = %.2f ", ((Point )p)->y); }}^ break; printf("\n"); }

The qsort Function

  • Some of the most useful functions in the C library require a function pointer as an argument.
  • One of these is qsort, which belongs to the <stdlib.h> header.
  • qsort is a general-purpose sorting function that’s capable of sorting any array. - Assume that the array to be sorted is indexed from 1 to n. qsort algorithm
  1. Choose an array element e (the “partitioning element”), then rearrange the array so that elements 1, …, i – 1 are less than or equal to e , element i contains e, and elements i + 1, …, n are greater than or equal to e.
  2. Sort elements 1, …, i – 1 by using Quicksort recursively.
  3. Sort elements i + 1, …, n by using Quicksort recursively.

The qsort Algorithm

The qsort Algorithm

  • Example of partitioning an array: Patitioning element

The qsort Function

  • qsort must be told how to determine which of two array elements is “smaller.”
  • This is done by passing qsort a pointer to a comparison function.
  • When given two pointers p and q to array elements, the comparison function must return an integer that is: o Negative if *p is “less than” *q o Zero if *p is “equal to” *q o Positive if *p is “greater than” *q

The qsort Function

  • Prototype for qsort: *void qsort(void base, size_t nmemb, size_t size, *int (compar)(const void , const void ));
  • base must point to the first element in the array (or the first element in the portion to be sorted).
  • nmemb is the number of elements to be sorted.
  • size is the size of each array element, measured in bytes.
  • compar is a pointer to the comparison function.
  • When qsort is called, it sorts the array into ascending order, calling the comparison function whenever it needs to compare array elements.

The qsort Example

**int vs[] = {40, 10, 100, 90, 20, 25}; int comp ( const void a, const void b){ return ( (int)a - (int)b ); } int main () { qsort (vs, 6, sizeof(int), comp); }

The qsort Function

  • A version of compare_parts that can be used to sort the inventory array by part name instead of part number: int compare_parts(const void *p, const void *q) { return strcmp(((struct part *) p)->name, ((struct part *) q)->name); }

Other Uses of Function Pointers

  • Although function pointers are often used as arguments, that’s not all they’re good for.
  • C treats pointers to functions just like pointers to data.
  • They can be stored in variables or used as elements of an array or as members of a structure or union.
  • It’s even possible for functions to return function pointers.

Other Uses of Function Pointers

  • A variable that can store a pointer to a function with an int parameter and a return type of void: void (*pf)(int);
  • If f is such a function, we can make pf point to f in the following way: pf = f;
  • We can now call f by writing either (*pf)(i); or pf(i);

Other Uses of Function Pointers

  • An array whose elements are function pointers: void (*file_cmd[])(void) = {new_cmd, open_cmd, close_cmd, close_all_cmd, save_cmd, save_as_cmd, save_all_cmd, print_cmd, exit_cmd };

Other Uses of Function Pointers

  • A call of the function stored in position n of the file_cmd array: (file_cmd[n])(); / or file_cmdn; */
  • We could get a similar effect with a switch statement, but using an array of function pointers provides more flexibility.

Program: Tabulating the Trigonometric Functions

  • The tabulate.c program prints tables showing the values of the cos, sin, and tan functions.
  • The program is built around a function named tabulate that, when passed a function pointer f, prints a table showing the values of f.
  • tabulate uses the ceil function.
  • When given an argument x of double type, ceil returns the smallest integer that’s greater than or equal to x.

Program: Tabulating the Trigonometric Functions

  • A session with tabulate.c: Enter initial value: 0 Enter final value:. Enter increment:. x cos(x) ------- 0.00000 -------1. 0.10000 0. 0.20000 0. 0.30000 0. 0.40000 0. 0.50000 0.

Program: Tabulating the Trigonometric Functions

-------^ x^ -------sin(x) 0.00000 0. 0.10000 0. 0.20000 0. 0.30000 0. 0.40000 0. 0.50000 0. -------^ x^ -------tan(x) 0.00000 0. 0.10000 0. 0.20000 0. 0.30000 0. 0.40000 0. 0.50000 0. tabulate.c /* Tabulates values of trigonometric functions / #include <math.h> #include <stdio.h> void tabulate(double double (f)(double),last, double incr);double first, int { main(void) double final, increment, initial; printf("Enter initial value: "); scanf("%lf", &initial); printf("Enter final value: "); scanf("%lf", &final); printf("Enter increment: "); scanf("%lf", &increment); printf("\n "\n (^) -------x (^) -------\n");cos(x)" tabulate(cos, initial, final, increment); printf("\n "\n (^) -------x (^) -------\n");sin(x)" tabulate(sin, initial, final, increment); printf("\n "\n (^) -------x (^) -------\n");tan(x)" tabulate(tan, initial, final, increment); }^ return^ 0; void tabulate(double (*f)(double), double first, { double^ last,^ double^ incr) double int i, x;num_intervals; num_intervals = ceil((last - first) / incr); for x (i= first= 0; i+ <=i num_intervals; incr; i++) { }^ printf("%10.5f^ %10.5f\n",^ x,^ (f)(x)); }