jtsk-320112*2mm programming in c ii*2mm c-lab ii*8mm...

63
JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch

Upload: others

Post on 22-Oct-2019

20 views

Category:

Documents


0 download

TRANSCRIPT

JTSK-320112

Programming in C II

C-Lab II

Lecture 3 & 4

Xu (Owen) He

Spring 2018

Slides modified from Dr. Kinga Lipskoch

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Planned Syllabus

I The C Preprocessor

I Bit Operations

I Pointers and Arrays (Dynamically AllocatedMulti-Dimensional Arrays)

I Pointers and Structures (Linked Lists)

I Compiling, Linking and the make Utility

I Pointers and Functions (Function Pointers)

I Stacks and Queues

I Modifiers and Other Keywords

I Binary I/O (File Handling)

C-Lab II Spring 2018 2 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Structures

I A structure (i.e., struct) is a collection of variablesI Variables in a structure can be of different types

I The programmer can define its own structuresI Once defined, a structure is like a basic data type, you can

defineI Arrays of structures,I Pointers to structures,I ...

C-Lab II Spring 2018 3 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Example: Points in the Plane

I A point is an object with two coordinates (= two properties)I Each one is a double value

I Problem: Given two points, find the point lying in the middleof the connecting segment

I It would be useful to have a point data typeI C does not provide such a type, but it can be defined

C-Lab II Spring 2018 4 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Defining the point struct

I The keyword struct can be used to define a structure

1 struct point {

2 double x;

3 double y;

4 };

I A point is an object with two doubles, called x and y of typedouble

C-Lab II Spring 2018 5 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Defining point Variables

I To declare a point (i.e., a variable of data type point), theusual syntax is used: type followed by variable namestruct point a, b;

I a and b are two variables of type struct point

C-Lab II Spring 2018 6 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Accessing the Components of a struct

To access (read / write) the components (i.e., fields) of astructure, the selection operator . is used

1 struct point a;

2 a.x = 34.5;

3 a.y = 0.45;

4 a.x = a.y;

C-Lab II Spring 2018 7 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

struct Initialization

I Like in the case of arrays, a structure can be initialized byproviding a list of initializersstruct point a = { 3.0, 4.0 };

I Initializations can use explicit field names to improvereadability and code robustness (e.g., if struct definitions aremodified)struct point a = { .x = 3.0, .y = 4.0 };

I As for arrays, it would be an error to provide more initializersthan members available

I Initializers’ types must match the types of the fields

C-Lab II Spring 2018 8 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

struct Assignment

I The assignment operator (=) can be used also with structures

1 struct point a, b;

2 a.x = a.y = 0.2345;

3 b = a;

I The copying is performed field by field (keep this in mindwhen your structures have pointers)

I Warning: the relational operators (including equality test) arenot defined for structures

C-Lab II Spring 2018 9 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Structures and Functions

A function can have parameters of type structure and can returnresults of type structure

1 struct point middle(struct point a,

struct point b) {

2 struct point retp;

3 retp.x = (a.x + b.x ) / 2;

4 retp.y = (a.y + b.y ) / 2;

5 return retp;

6 }

C-Lab II Spring 2018 10 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Arrays of Structures

I It is possible to define arrays of structures

I The selection operator must then be applied to the elementsin the array (as every element is a structure)

1 struct point list [4];

2 list [0].x = 3.0;

3 list [0].y = 7.3;

C-Lab II Spring 2018 11 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Pointers to Structures

I Structures reside in memory, thus it is possible to get theiraddress

I Everything valid for the basic data types still holds forpointers to structures

1 struct point p;

2 struct point *pointpointer;

3 pointpointer = &p;

C-Lab II Spring 2018 12 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

The Arrow Operator

I A structure can be modified by using a pointer to it and thedereference operator(*pointpointer).x = 45;

I Parenthesis are needed to adjust the precedence of theoperators * and .

I The arrow operator achieves the same goal giving the sameresultpointpointer->x = 45;

C-Lab II Spring 2018 13 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Dynamic Structures

I Pointers to structures can be used to allocate dynamicallysized arrays of structures

1 struct point *ptr;

2 int number;

3 scanf("%d\n", &number);

4 ptr = (struct point *) malloc(sizeof(

5 struct point) * number);

I You can access the array as we have already seen

1 ptr[0] = { 0.9, 9.87 };

2 ptr [1].x = 7.45;

3 ptr [1].y = 57.3;

C-Lab II Spring 2018 14 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Pointers and Structures: Self-referential Structures

I Is it possible for a structure A to have a field of type A? NoI Is it possible for a structure A to have a field which is a

pointer to A? YesI This is called self referenceI You will encounter many data structures organized by mean of

self references

I Trees, Lists, ...

C-Lab II Spring 2018 15 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

An Example: Lists

I A list is a data structure in which objects are arranged in alinear order

I The order in a list is determined by a pointer to the nextelement

I While a vector has indices

I Advantages: lists can grow and shrink

I Disadvantages: access is not efficient

C-Lab II Spring 2018 16 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Linked Lists

I It is a standard way to represent listsI A list of integers: every element holds an int plus a pointer to

the next oneI Recursive definition

I The last element’s pointer points to NULL

34 18 5

NULL

C-Lab II Spring 2018 17 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Linked Lists in C

I Every element (node) holds two different informationI The value (integer, float, double, char, array, ...)I Pointer to the next element

I This ”calls” for a structure

1 struct list {

2 int info;

3 struct list *next; /* self reference */

4 };

C-Lab II Spring 2018 18 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Building the Linked List

1 struct list a, b, c;

2 struct list *my_list;

3 my_list = &a;

4 a.info = 34;

5 a.next = &b;

6 b.info = 18;

7 b.next = &c;

8 c.info = 5;

9 c.next = NULL; /* defined in stdlib.h */

I NULL is a constant indicating that the pointer is not holding avalid address

I In self-referential structures it is used to indicate the end ofthe data structure

C-Lab II Spring 2018 19 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Printing the Elements of a Linked List

1 void print_list(struct list* my_list) {

2 struct list *p;

3 for(p = my_list; p; p = p->next) {

4 printf("%d\n", p->info);

5 }

6 }

7 /* Using a while loop

8 void print_list(struct list* my_list) {

9 while (my_list != NULL) {

10 printf ("%d\n", my_list ->info);

11 my_list = my_list ->next;

12 }

13 }*/

To print all the elements of a list, print_list should be calledwith the address of the first element in the list

C-Lab II Spring 2018 20 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Dynamic Growing and Shrinking

I Elements added and deleted to lists are usually allocateddynamically using the malloc and free functions

I The example we have seen before is not the usual case (weassumed the list has content)

I Initially the list is set to empty (i.e., it is just a NULL pointer)struct list *my_list = NULL;

C-Lab II Spring 2018 21 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Inserting an Element in a Linked List (1)

1 /* Inserts a new int at the beginning of the list

2 my_list list where element should be inserted

3 value integer to be inserted

4 Returns the updated list

5 */

6

7 struct list* push_front(struct list *my_list , int value) {

8 struct list *newel;

9 newel = (struct list *) malloc(sizeof(struct list));

10 if (newel == NULL) {

11 printf("Error allocating memory\n");

12 return my_list;

13 }

14 newel ->info = value;

15 newel ->next = my_list;

16 return newel;

17 }

C-Lab II Spring 2018 22 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Inserting an Element in a Linked List (2)1 /* Like the previous one , but inserts at the end */

2

3 struct list* push_back(struct list* my_list , int value) {

4 struct list *cursor , *newel;

5 cursor = my_list;

6 newel = (struct list *) malloc(sizeof(struct list));

7 if (newel == NULL) {

8 printf("Error allocating memory\n");

9 return my_list;

10 }

11 newel ->info = value;

12 newel ->next = NULL;

13 if (my_list == NULL)

14 return newel;

15 while (cursor ->next != NULL)

16 cursor = cursor ->next;

17 cursor ->next = newel;

18 return my_list;

19 }

C-Lab II Spring 2018 23 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Freeing a Linked List

1 /*

2 Disposes a previously allocated list

3 */

4

5 void dispose_list(struct list* my_list) {

6 struct list *nextelem;

7 while (my_list != NULL) {

8 nextelem = my_list ->next;

9 free(my_list);

10 my_list = nextelem;

11 }

12 }

C-Lab II Spring 2018 24 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Using a Linked Lists

1 /*

2 Here go the definitions we have seen before

3 */

4

5 int main() {

6 struct list* my_list = NULL;

7

8 my_list = push_front(my_list , 34);

9 my_list = push_front(my_list , 18);

10 my_list = push_back(my_list , 56);

11 print_list(my_list);

12 dispose_list(my_list);

13 }

C-Lab II Spring 2018 25 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Doubly Linked Lists

34 18 5

NULL

NULL

C-Lab II Spring 2018 26 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Circular Doubly Linked Lists

5

27

34

18

C-Lab II Spring 2018 27 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Declarations and Definitions

I Declaration: Introduces an object. After declaration theobject can be used

I Example: functions prototypes

I Definition: Specifies the structure of an objectI Example: function definition

I Declarations can appear many times, definitions just once

C-Lab II Spring 2018 28 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Dealing with Larger Programs

I Functions are a first step to break big programs in smalllogical units

I Breakup of specific tasks into functions

I A further step consists in breaking the source into manymodules (files)

I Smaller files are easy to handleI Objects sharing a context can be put together in one module

and easily reused

I C allows to put together separately compiled files to have oneexecutable

C-Lab II Spring 2018 29 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Libraries

I Libraries are collections of compiled definitions

I You include header files to get the declarations of objects inlibraries

I At linking time libraries are searched for unresolveddeclarations

I Some libraries are included by gcc even if you do notspecifically ask for them

C-Lab II Spring 2018 30 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Example: Linking math Functions

1 #include <math.h>

2 #include <stdio.h>

3

4 int main() {

5 double n;

6 double sn;

7

8 scanf("%lf", &n); /* double needs %lf */

9 sn = sqrt(n);

10 /* conversion from double to float ok */

11 printf("Square root of %f is %f\n", n, sn);

12 return 0;

13 }

gcc -lm -o compute compute.c

C-Lab II Spring 2018 31 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Building from Multiple Sources

I C compilers can compile multiple sources files into oneexecutable

I For every declaration there must be one definition in one ofthe compiled files

I Indeed also libraries play a roleI This control is performed by the linker

I gcc -o name file1.c file2.c file3.c

C-Lab II Spring 2018 32 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Linking

Source 1Source 2

(*.c)Source 3

(*.c)Source 4

(*.c)Source 5

(*.c)Source 1

(*.c)

Object 1(*.o)

Object 2(*.o)

Object 3(*.o)

Object 4(*.o)

Object 5(*.o)

Executable

C o m p i l e r

L i n k e rExternal References

gcc ­c *.c

gcc *.o

C-Lab II Spring 2018 33 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Linked List Header File1 /* *******************************************************

2 * *

3 * A simply linked list is linked from node structures *

4 * whose size can grow as needed. Adding more elements *

5 * to the list will just cause it to grow and removing *

6 * elements will cause it to shrink.

7 *------------------------------------------------------*

8 * struct ll_node *

9 * used to hold the information for a node of a *

10 * simply linked list *

11 *------------------------------------------------------*

12 * Function declaration (routines) *

13 * *

14 * push_front -- add an element in the beginning *

15 * push_back -- add an element in the end *

16 * dispose_list -- remove all the elements *

17 * ... *

18 ******************************************************* */

C-Lab II Spring 2018 34 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Definition Import via #include

#include “linked_list.h”

use_linked_list.c

Usage of the linked list

linked_list.h

#include “linked_list.h”

linked_list.c

Implementationof the linked list

C-Lab II Spring 2018 35 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Compile Linked List from Multiple Sources

I Create a project with your IDE, add all files including theheader file and then compile and execute

I or

I Compile: gcc -Wall -o use_linked_list linked_list.c

use_linked_list.c

I Execute: ./use_linked_list

C-Lab II Spring 2018 36 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Cygwin

I Cygwin is a Unix-like environment and command-line interfacefor Microsoft Windows

I Cygwin provides native integration of Windows-basedapplications, data, and other system resources withapplications, software tools, and data of the Unix-likeenvironment

I Thus it is possible to launch Windows applications from theCygwin environment, as well as to use Cygwin tools andapplications within the Windows operating context

C-Lab II Spring 2018 37 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Install Cygwin on Windows (1)

I Go to https://cygwin.com/install.html, downloadsetup-x86_64.exe and install it

I During installation add gdb, gcc-core and make listed underDevel

C-Lab II Spring 2018 38 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Install Cygwin on Windows (2)

I Once installed under C:/cygwin64 you will have a Unix-likeenvironment

I You can use it to compile and debug your code using gcc andgdb

C-Lab II Spring 2018 39 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

make (1)

I make is special utility to help programmer compiling andlinking programs

I Programmers had to type in compile commands for everychange in program

I With more modules more files need to be compiledI Possibility to write script, which handles sequence of compile

commands

I Inefficient

C-Lab II Spring 2018 40 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

make (2)

I Compiling takes time

I For only small change in one module, not necessary torecompile other modules

I make: compilations depends upon whether file has beenupdated since last compilation

I Also possible to specify dependencies

I Also possible to specify commands to compile (e.g.,depending of suffix of source)

C-Lab II Spring 2018 41 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Makefile (1)

I A makefile has the name ”Makefile”I Makefile contains following sections:

I CommentsI MacrosI Explicit rulesI Default rules

C-Lab II Spring 2018 42 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Makefile (2)

I CommentsI Any line that starts with a # is a comment

I Macro formatI name = dataI Ex: OBJ=linked_list.o use_linked_list.oI Can be referred to as $(OBJ) from now on

C-Lab II Spring 2018 43 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Makefile (3)

Explicit rules

I target:source1 [source2] [source3]

command1

[command2]

[command3]

I target is the name of file to create

I File is created from source1 (and source2, ...)

I use_linked_list: use_linked_list.o linked_list.o

gcc -o use_linked_list

use_linked_list.o linked_list.o

C-Lab II Spring 2018 44 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Makefile (4)

Explicit rules

I target:

command

Commands are unconditionally executed each time make is run

I Commands may be omitted, built-in rules are used then todetermine what to douse_linked_list.o: linked_list.h use_linked_list.c

I Create use_linked_list.o from linked_list.h anduse_linked_list.c using standard suffix rule for getting touse_linked_list.o from linked_list.c

I $(CC) $(CFLAGS) -c file.c

C-Lab II Spring 2018 45 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Example Makefile

1 CC = gcc

2 CFLAGS = -Wall

3

4 OBJ = linked_list.o use_linked_list.o

5

6 all: use_linked_list

7

8 use_linked_list: $(OBJ)9 $(CC) $(CFLAGS) -o use_linked_list $(OBJ)

10

11 use_linked_list.o: linked_list.h use_linked_list.c

12

13 linked_list.o: linked_list.h linked_list.c

14

15 clean:

16 rm -f use_linked_list *.o

C-Lab II Spring 2018 46 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function Pointers

I A pointer may not just point to a variable, but may also pointto a function

I In the program it is assumed that the function does what ithas to do and you use it in your program as if it was there

I The decision which function will actually be called isdetermined at run-time

C-Lab II Spring 2018 47 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function Pointer Syntax

I void (*foo)(int);

I foo is a pointer to a function taking one argument, an integer,and that returns void

I void *(*foo)(int *);

I foo is a pointer to a function that returns a void * and takesan int * as parameter

I int (*foo_array[2])(int);

I foo_array is an array of two pointer functions having an int

as parameter and returning an int

I Easier and equivalent:typedef int (*foo_ptr_t)(int);

foo_ptr_t foo_ptr_array[2];

C-Lab II Spring 2018 48 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function Pointers: Simple Examples

1 void (*func) (); /* define pointer to function */

2 void a() { printf("func a\n"); }

3 void b() { printf("func b\n"); }

4

5 int main() {

6 func = &a; // calling func() is the same as calling a()

7 func = a; // calling func() is the same as calling a()

8 func();

9 }

One may have an array of function pointers:

1 int func1();

2 int func2();

3 int func3();

4 int (* func_arr [3])() = {func1 , func2 , func3};

C-Lab II Spring 2018 49 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Another Function Pointer Example1 #include <stdio.h>

2 void output(void) {

3 printf("%s\n", "Please enter a number:");

4 }

5 int sum(int a, int b) {

6 return (a + b);

7 }

8 int main() {

9 int x, y;

10 void (*fptr1)(void);

11 int (*fptr2)(int , int);

12 fptr1 = output;

13 fptr2 = sum;

14 fptr1(); // cannot see whether function or pointer

15 scanf("%d", &x);

16 (fptr1)(); // some prefer this to show it is pointer

17 (*fptr1)(); // complete syntax , same as above

18 scanf("%d", &y);

19 printf("The sum is %d.\n", fptr2(x, y));

20 }

C-Lab II Spring 2018 50 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Alternatives for Usage

1 int (*fct) (int , int);

2 /* define pointer to a fct */

3 int plus(int a, int b) {return a+b;}

4 int minus(int a, int b) {return a-b;}

5 int a=3; int b=4;

6 fct = &plus;

7 /* calling fct() same as calling plus() */

8 printf("fct(a,b):%d\n", fct(a,b)); /* 7 */

or

1 printf("fct(a,b):%d\n", (*fct)(a,b)); /* 7 */

2 fct = &minus;

3 /* calling fct() same as calling minus() */

4 printf("fct(a,b):%d\n", fct(a,b)); /* -1 */

C-Lab II Spring 2018 51 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Printing a List with Function Pointers1 void foreach_list_simple(struct list *my_list ,

void (*func)(int num)) {

2 struct list *p;

3 for (p = my_list; p != NULL; p = p->next) {

4 func(p->info);

5 }

6 }

7 void printnum(int num) {

8 printf("%d ", num);

9 }

10 int main() {

11 ...

12 foreach_list_simple(my_list , printnum);

13 return 0;

14 }

C-Lab II Spring 2018 52 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Summing Up a List with Function Pointers1 void foreach_list(struct list *my_list ,

2 void (*func)(int num , void *state),

3 void *state) {

4 struct list *p;

5 for (p = my_list; p != NULL; p = p->next) {

6 func(p->info , state);

7 }

8 }

9 void sumup(int num , void *state) {

10 int *p = (int *) state;

11 *p += num;

12 }

13 int main() {

14 ...

15 int sum = 0;

16 foreach_list(my_list , sumup , &sum);

17 printf("sum=%d\n", sum); return 0;

18 }

C-Lab II Spring 2018 53 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Sorting with Function Pointers

I An array of lines (strings) can be sorted according to multiplecriteria:

I Lexicographic comparison of two lines (strings) is done bystrcmp()

I Function numcmp() compares two lines on the basis of numericvalue and returns the same kind of condition indication asstrcmp does

I These functions are declared ahead of the main and a pointerto the appropriate one is passed to the function qsort

(implementing quick sort)

C-Lab II Spring 2018 54 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function strcmp()I strcmp() compares the two strings s1 and s2

I It returns an integer less than, equal to, or greater than zero ifs1 is found, respectively, to be less than, to match, or begreater than s2

1 #include <stdio.h>

2 #include <string.h>

3 int main() {

4 char s1[30], s2[30];

5 scanf("%29s", s1);

6 scanf("%29s", s2);

7 // avoid buffer overflow on the strings

8 if (! strcmp(s1, s2)) {

9 printf("Both strings are equal !\n");

10 }

11 return 0;

12 }

C-Lab II Spring 2018 55 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function numcmp()

I Functionstrcmp()

compares twostrings andreturns <0, 0, >0

I Here you seefunctionnumcmp(), whichcompares twostrings on aleading numericvalue, computedby calling atof

1 #include <stdlib.h>

2 /* numcmp: compare s1 and s2

numerically */

3 int numcmp(char *s1 , char *s2 ){

4 double v1 , v2;

5 v1 = atof(s1);

6 v2 = atof(s2);

7 if (v1 < v2)

8 return -1;

9 else if (v1 > v2)

10 return 1;

11 else

12 return 0;

13 }

C-Lab II Spring 2018 56 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Further Refinement of the Sorting Problem

I You want to write a sorting function

I The sorting algorithm is the same, but the comparisonfunction may be different (i.e., you want ordering by differentkeys, different data types, increasing/decreasing sequence)

I Can we have a pointer to a comparison function as parameterfor the sort function and write the sort function only once,always calling it with different comparison functions?

C-Lab II Spring 2018 57 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Function Pointer as Function Argument

1 int my_sort(int *array , int n,

2 int (* my_cmp) (int ,int)) {

3 ...

4 if ( my_cmp(array[i],array[i+1]) == 1) {

5 ...

6 }

7 ...

8 }

C-Lab II Spring 2018 58 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Usage of Function Pointers as Function Arguments

1 int fct1(int a, int b) {

2 ...

3 }

4 int *array , n;

5 /* pass your function as argument */

6 my_sort(array , n, &fct1);

C-Lab II Spring 2018 59 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Using the qsort() from stdlib.h

This version of the qsort is declared in stdlib.h:

1 void qsort(void *base ,

2 size_t nmemb ,

3 size_t size ,

4 int(* compare)(const void *,

5 const void *));

C-Lab II Spring 2018 60 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

User Supplied Comparison Function

1 int my_compare(const void *va , const void *vb) {

2 const int* a = (const int*) va;

3 const int* b = (const int*) vb;

4 if (*a < *b) return -1;

5 else if (*a > *b) return 1;

6 else return 0;

7 }

C-Lab II Spring 2018 61 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Calling qsort()

1 #include <stdio.h>

2 #include <stdlib.h>

3 #include <time.h>

4 #define NUM_ELEMENTS 50

5 int my_compare(const void *va, const void *vb) {

6 const int* a = (const int*) va;

7 const int* b = (const int*) vb;

8 if (*a < *b) return -1;

9 else if (*a > *b) return 1;

10 else return 0;

11 }

12 int main() {

13 srand(time(NULL)); // initialize random number generator

14 int arr[NUM_ELEMENTS ];

15 int i;

16 /* fill array with random numbers */

17 for (i = 0; i < NUM_ELEMENTS; i++)

18 arr[i] = rand() % 1000;

19 qsort(arr , NUM_ELEMENTS , sizeof(arr [0]), my_compare);

20 for (i = 0; i < NUM_ELEMENTS; i++)

21 printf("%d\n", arr[i]);

22 return 0;

23 }

C-Lab II Spring 2018 62 / 63

Structures Self-referential Structures Linked Lists Compiling and Linking make Function Pointers Comparison Functions

Why useful?

I Can use qsort() or other functions with your own data types(struct), just need to write the comparison function, but noneed to duplicate the sorting function itself

I Change comparison function to reverse the order

I Change comparison function to sort by different key (memberof your struct), e.g., sort by first name, last name, age, ...

C-Lab II Spring 2018 63 / 63