Generic Functions1 Generic Functions: A generic function is one that can work on any underlying C data type. Generic functions allow us to reuse programs.

Slides:



Advertisements
Similar presentations
Numeric Types & Ranges. ASCII Integral Type Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite.
Advertisements

Stacks, Queues, and Linked Lists
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
1 Homework / Exam HW7 due class 25 Exam 3 - class 26 –Open Book, Open Notes –Covers up through end of K&R 7 –and Appendix B Standard Library –Plus UNIX.
Memory Image of Running Programs Executable file on disk, running program in memory, activation record, C-style and Pascal-style parameter passing.
Pointers Chapters 6+9 in ABC. abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
Advanced pointer topics (Reek, Ch. 13) 1CS 3090: Safety Critical Programming in C.
Built into qsort is a function that can swap two given array elements.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Pointers OVERVIEW.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
System Programming Practical Session 7 C++ Memory Handling.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
1 Homework Continue with K&R Chapter 5 –Skipping sections for now –Not covering section 5.12 Continue on HW5.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Generic Programming in C
Stack and Heap Memory Stack resident variables include:
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
A bit of C programming Lecture 3 Uli Raich.
Characters and Strings
Student Book An Introduction
Popping Items Off a Stack Lesson xx
Data Structures and Algorithms
Programming Linked Lists.
כתיבת מאקרו הפקודה assert מצביעים לפונקציות
Miscellaneous functions
Pointers Lecture 2 Tue, Jan 24, 2006.
CS111 Computer Programming
프로그래밍2 및 실습 Sort Code 전명중.
Presentation transcript:

Generic Functions1 Generic Functions: A generic function is one that can work on any underlying C data type. Generic functions allow us to reuse programs by adding a small piece of type-specific code. For example, standard C library provides two generic functions: bsearch searches an arbitrary array, and qsort sorts an arbitrary array.

Generic Functions2 Review of Pointers to Functions: A pointer to a function contains the address of the function in memory. Similar to an array name which is the starting address of the first array element, a function name is the starting address of the function code. Pointers to functions can be passed to functions, returned from functions, stored in an array, and assigned to other function pointers.

Generic Functions3 Pointers to Functions: int compare(int a, int b){ // implementation } int main(){ int cr1, cr2; int (*pf)(int, int); // declare a pointer to function pf = compare; // assign a function pointer to pf cr1 = (*pf)(2, 3); // call the function cr2 = pf(2, 3); // same as above but not recommended }

Generic Functions4 Generic Binary Search: void * bserach(const void *target, const void *table, size_t n, size_t size, int (*cmpfp)(const void *, const void*)); target: a pointer to the element we are searching for table: the array we are searching n: the size of the array size: the size of an array element cmpfp: a pointer to a function to compare the target and an element … n size table target Target element

Generic Functions5 bsearch Function: void * bserach(const void *target, const void *table, size_t n, size_t size, int (*cmpfp)(const void *, const void*)){ void *min = table, *max = table + (n – 1)*size; void *mid; int k = n/2; int cr; while (min < max) { mid = min + k*size cr = (*cmpfp)(target, mid) ; if (cr == 0) return mid; else if (cr > 0) min = mid + size; else max = mid - size; k /= 2; } return NULL; }

Generic Functions6 Invoking bsearch: bsearch returns a pointer to the matching array element if it finds one, or NULL otherwise. Suppose we have an int table intTable and a string table stringTable, we might call: int key = 78; int* ip = bsearch(&key, intTable, ISIZE, sizeof(int), cmpInt); char* sp = bsearch(“Tom Wilson”, stringTable, SSIZE, sizeof(stringTable[0]), cmpStr);

Generic Functions7 Type-specific Functions: int cmpInt(const void *tp, const void *ep){ int it = *(int*) tp; // get target value int ie = *(int*) ep; // get array element value return (it == ie) ? 0 : ((it < ie) ? –1 : 1); } int cmpStr(const void *tp, const void *ep){ char *ctp = (char*) tp; // casting target to char pointer char *cep = *(char**) ep; // get array element value (a char pointer) return strcmp(ctp, cep); }

Generic Functions8 Another Example: In-place insertion-sort an array of integers: void isort_int(int table[], int n){ int j, k, temp; for (j = 1; j < n; j++){ temp = table[j]; for (k = j; k > 0; k--){ if (temp >= table[k-1]) break; table[k] = table[k-1]; } table[k] = temp; }

Generic Functions9 Generic insertion-sort: #include void isort_generic(void *table, int n, size_t size, int (*cmp)(const void*, const void*)){ char *sp = table, *pj, *pk; char *ep = sp + n*size; void * temp = malloc(size); for (pj = sp + size; pj < ep; pj +=size){ memcpy(temp, pj, size); for (pk = pj; pk > sp; pk -= size){ if ((*cmp)(temp, pj – size) >= 0) break; memcpy(pk, pk – size, size); } memcpy(pk, temp, size); } free(temp); } void isort_int(int table[], int n){ int j, k, temp; for (j = 1; j < n; j++){ temp = table[j]; for (k = j; k > 0; k--){ if (temp >= table[k-1]) break; table[k] = table[k-1]; } table[k] = temp; }

Generic Functions10 Call isort_generic: Suppose we have along table longTable, and a string table stringTable, we might call: isort_generic(intTable, TSIZE, sizeof(longTable[0]), cmpLong); isort_generic(stringTable, SSIZE, sizeof(stringTable[0]), cmpStrs); How to implement cmpLong and cmpStrs?

Generic Functions11 int cmpLong(const void *p1, const void *p2){ long lp1, lp2; lp1 = *(long*) p1; lp2 = *(long*) p2; return lp1 – lp2; // or even better: return *(long*) p1 - *(long*) p2; } int cmpStrs(const void *p1, const void *p2){ // for isort_generic return strcmp(*(char**) p1, *(char**) p2); } /* what is the difference of cmp functions for isort and bsearch? */ int cmpStr(const void *tp, const void *ep){ // for bsearch char *ctp = (char*) tp; // casting target to char pointer char *cep = *(char**) ep; // get array element value (a char pointer) return strcmp(ctp, cep); }

Generic Functions12 Example: A Stack-based Calculator Use command-line arguments as input and calculate basic arithmetic wrt the given data and operations. The program interprets the following operations: +: pop two numbers, add them and push the result back -: pop two numbers, subtract them and push the result back mul: pop two numbers, multiply them and push the result back (**) /: pop two numbers, divide them and push the result back xchg: exchange the top two elements print: pop and print the top element dup: duplicate the top element Example: $calc 4 dup dup mul xchg 2 / - print 4 * 4 – 4/2

Generic Functions13 (**) Why dotn’t use * instead of mul? Because different shells have different meanings if * is used as the command line argument. For example, Bash interprets * as file names of the current directory. Suppose there are three files under the current dir: $prog * argc = 4 argv[0] = “prog” argv[1] = “f1.c” argv[2] = “f1.o” argv[3] = “f1.h”

Generic Functions14 #include typedef struct node node; struct node{ double n; node* next; }; #define empty() !(stk) node* stk = NULL; void push(double n){ node * new = (node*) malloc(sizeof(node)); if (!new) exit(-1); new->n = n; new->next = stk; stk = new; }

Generic Functions15 double pop(){ double n; node* t; if (empty()) return 0.0; t = stk; n = stk->n; stk = stk->next; free(t); return n; } void add(){ double b = pop(); push(pop() + b); } void sub(){ double b = pop(); push(pop() - b); }

Generic Functions16 void fmul(){ double b = pop(); push(pop() * b); } void fdiv(){ double b = pop(); push(pop() / b); } void xchg(){ double a = pop(); double b = pop(); push(a); push(b); }; void print(){ printf("Result = %f\n", pop()); }

Generic Functions17 void dup(){ double b = pop(); push(b); } char* operation[] ={ "+", "-", "mul", "/", "xchg", "print", "dup"}; void (*action[])() = {add, sub, fmul, fdiv, xchg, print, dup}; void exec(char * cmd){ int i; for (i = 0; i < sizeof(operation)/sizeof(char*); i++){ if (strcmp(cmd, operation[i]) == 0){ (*action[i])(); return; } printf(“Illegal operation %s\n”, cmd); }

Generic Functions18 int main(int argc, char* argv[]){ int i; for (i = 1; i < argc; i++){ if (isdigit(argv[i][0])) push(atof(argv[i])); else exec(argv[i]); } exit(0); }