1 Function Pointers and Abstract Data Types CS 217.

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

Introduction to C Programming
C Language.
Lectures 10 & 11.
Data Structure & Abstract Data Type
One Dimensional Arrays
Programming and Data Structure
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Chapter 10.
CS414 C Programming Tutorial Ben Atkin
1 Generics Professor Jennifer Rexford
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
Numbers and Arrays. Widening and narrowing Numeric types are arranged in a continuum: double float long int short byte, char You can easily assign a narrower.
1 Midterm Review (overview of fall 2005 midterm) Professor Jennifer Rexford COS 217.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Midterm Review (overview of fall 2005 midterm) Professor Jennifer Rexford COS 217.
Aalborg Media Lab 15-Jul-15 Polymorphism Lecture 12 Chapter 9.
1 Function Pointers and Abstract Data Types Professor Jennifer Rexford COS 217.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
1 Project 5: Median. 2 The median of a collection of numbers is the member for which there are an equal number less than or equal and greater than or.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Arrays Chapter 13 Especially read 13.1 – 13.2 Text introduces vectors, which we will not cover, in 13.3.
Types for Programs and Proofs Lecture 1. What are types? int, float, char, …, arrays types of procedures, functions, references, records, objects,...
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable.
Data Types. Data types Data type tells the type of data, that you are going to store in memory. It gives the information to compiler that how much memory.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
1 Interfaces Reading for today: Sec and corresponding ProgramLive material. Also, compare with previous discussions of abstract classes (Sec. 4.7).
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Lecture4: Arrays Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Overview of C++ Templates
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
142 L -1 Pointers Chapter 6 C uses a call BY VALUE for functions for example: void add_one(int x, int y) { x=x+1; y=y+1; } int main(void) { int a,b; a=4;
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Gator Engineering Project 1 Grades released Re-grading –Within one week –TA: Fardad, or office hours: MW 2:00 – 4:00 PM TA Huiyuan’s office hour.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Reminders: Have you filled out the questionnaire in Moodle? (3 left – as of last night). Office hours.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
The C++ Data Types Fundamental Data Types
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Conversions of the type of the value of an expression
CS150 Introduction to Computer Science 1
Java Programming Language
Chapter 9: Pointers and String
Chapter 9: Pointers and String
Presentation transcript:

1 Function Pointers and Abstract Data Types CS 217

2 Reminder: Midterm Exam Exam logistics on Thu Oct 27  Date/time: Thursday October 27 at 10:00-10:50am (in lecture)  Open books, open notes, open mind, but not open laptop/PDA  Covering material from lecture, precept, and reading, but not tools Review in Thu Oct 13 lecture  Chris DeCoro will go over these practice questions –Fall 2002: #3, #5 –Spring 2002: #3, #7 –Spring 2004: #1, #4 –Fall 2004: #1, #3, #4, #5  I recommend you try the problems in advance  See Chris’ for other good practice problems to try  Answers to old exams made available online later this week

3 Goals of Today’s Lecture Function pointers  Sorting an array of integers  Sorting an array of strings  Sorting an array of any type –Void pointers and casting –Pointers to functions Abstract Data Types  Making “array” an ADT

4 Sorting an Array of Integers Example problem  Input: array v of n integers  Output: array in sorted order, from smallest to largest Many ways to sort, but three common aspects  Comparison between any two elements  Exchange to reverse the order of two elements  Algorithm that makes comparisons and exchanges till done Simple approach  Go one by one through the n array elements  By the end of step i, get i th smallest value in element i –Compare element i with all elements after it –Swap values if the i th element is larger

5 Integer Sorting Example v[0] > v[1]? Yes, swap 9627v[0] > v[2]? 9627v[0] > v[3]? 9627v[1] > v[2]? 9627v[1] > v[3]? Yes, swap 9726 …

6 Integer Sorting Function void sort(int *v, int n) { int i, j; for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { if (v[i] > v[j]) { int swap = v[i]; v[i] = v[j]; v[j] = swap; } comparison swap

7 Sorting an Array of Strings Data types are different  Array elements are char*  Swap variable is char* Comparison operator is different  The greater-than (“>”) sign does not work  Need to use strcmp() function instead “the” “quick” “brown” “fox” “the” “quick” “brown” “fox”

8 String Sorting Function void sort(char *v[], int n) { int i, j; for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { if (strcmp(v[i], v[j]) > 0) { char* swap = v[i]; v[i] = v[j]; v[j] = swap; } comparison swap

9 Creating a Generic Function Generic function  A single sort() function that works for all data types C’s notion of data types is getting in our way  We need to accept parameters in any type –sort(int *v, int n) is only good for integer arrays –sort(char *v[], int n) is only good for string arrays  We need to have local variables of any type –int swap is only good for swapping integers –char* swap is only good for swapping strings Different types need different comparison operators  Greater-than sign (“ > ”) is only good for numerical types  strcmp() is only good for strings  We need to be able to tell sort() what comparison function to use

10 Generalizing: Void Pointers Generic pointers are the same as any other pointer  Except they point to a variable with no specific type  Example: void *datap = “CS217”; Difference:  Regular pointers: compilers “know” what they point to  void pointers: compilers “don’t know” what they point to Common Uses:  Abstract data types supporting polymorphism*  Pass pointer to function that could be any of several types Memory 0x x xFFFFFFFF `C``S``2``1` `7``\0` datap * Allowing the same definitions to be used with different types of data

11 Void Pointers in Sort Function parameters  Input: array of pointers to some unknown type Local swap variable  Pointer to some unknown type But, what about the comparison step?  Need to be able to pass a function to sort void *swap = v[i]; v[i] = v[j]; v[j] = swap; void sort(void *v[], int n)

12 Casting: Explicit Type Conversions Casting  As if the expression were assigned to a variable of the specified type  E.g., int *intp1 cast into void pointer by (void *) intp1 C does many implicit conversions  E.g., function double sqrt(double) –Can be called as sqrt(2); –Which is treated as sqrt((double) 2); Sometimes useful to make conversion explicit  Documentation: making implicit type conversions explicit –E.g., getting the integer part of a floating-point number –Done by int_part = (int) float_number;  Control: overrule the compile by forcing conversions we want –E.g., getting the fractional part of a floating-point number –Done by frac_part = f – (int) f;

13 Generic Sort Function void sort(void *v[], int n, int (*compare)(void *datap1, void *datap2)) { int i, j; for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { if ((*compare)(v[i], v[j]) > 0) { void *swap = v[i]; v[i] = v[i]; v[j] = swap; } compare is a pointer to a function that has two void* arguments and returns an int, and (*compare) is the function.

14 Using Generic Sort With String #include #include “sort.h” int main() { char* w[4] = {“the”, “quick”, “brown”, “fox”}; sort((void **) w, 4, (int (*)(void*,void*)) strcmp); … } pointer to a function

15 Using Generic Sort With Integers #include #include “sort.h” int CompareInts(void *datap1, void *datap2) { int *intp1 = (int *) datap1; int *intp2 = (int *) datap2; return (*intp1 - *intp2); } int main() { int* w[4]; w[0] = malloc(sizeof(int)); *(w[0]) = 7; … sort((void **) w, 4, (int (*)(void*,void*))CompareInts); … } pointer to a function

16 Making “Array” an ADT Arrays in C are error prone  Access elements before the array starts (e.g., v[-1] )  Access elements past the end of array (e.g., v[n] )  Modify the variable that keeps track of size (e.g., n ) Protect programmers with an array ADT  Create and delete an array  Get the current length  Read an array element  Append, replace, remove  Sort

17 Array ADT: Interface typedef struct Array *Array_T; extern Array_T Array_new(void); extern void Array_free(Array_T array); extern int Array_getLength(Array_T array); extern void *Array_getData(Array_T array, int index); extern void Array_append(Array_T array, void *datap); extern void Array_replace(Array_T array, int index, void *datap); extern void Array_remove(Array_T array, int index); extern void Array_sort(Array_T array, int (*compare)(void *datap1, void *datap2)); array.h client does not know implementation

18 Client Using Array ADT: Strings #include “array.h” #include int main() { Array_T array; int i; array = Array_new(); Array_append(array, (void *) “COS217”); Array_append(array, (void *) “IS”); Array_append(array, (void *) “FUN”); for (i = 0; i < Array_getLength(array); i++) { char *str = (char *) Array_getData(array, i); printf(str); } Array_free(array); return 0; }

19 Client Using Array ADT: Integers #include “array.h” #include int main() { Array_T array; int one=1, two=2, three=3; int i; array = Array_new(); Array_append(array, (void *) &one); Array_append(array, (void *) &two); Array_append(array, (void *) &three); for (i = 0; i < Array_getLength(array); i++) { int *datap = (int *) Array_getData(array, i); printf(“%d “, *datap); } Array_free(array); return 0; }

20 Array ADT Implementation #include “array.h” #define MAX_ELEMENTS 128 struct Array { void *elements[MAX_ELEMENTS]; int num_elements; }; Array_T Array_new(void) { Array_T array = malloc(sizeof(struct Array)); array->num_elements = 0; return array; } void Array_free(Array_T array) { free(array); }

21 Array ADT Implementation (Cont) int Array_getLength(Array_T array) { return array->num_elements; } void *Array_getData(Array_T array, int index) { return array->elements[index]; } void Array_append(Array_T array, void *datap) { int index = array->num_elements; array->elements[index] = datap; array->num_elements++; } void Array_replace(Array_T array, int index, void *datap) { array->elements[index] = datap; }

22 Array ADT Implementation (Cont.) void Array_insert(Array_T array, int index, void *datap) { int i; /* Shift elements to the right to make room for new entry */ for (i = array->num_elements; i > index; i--) array->elements[i] = array->elements[i-1]; /* Add the new element in the now-free location */ array->elements[index] = str; array->num_elements++; } void Array_remove(Array_T array, int index) { int i; /* Shift elements to the left to overwrite freed spot */ for (i = index+1; i num_elements; i++) array->elements[i-1] = array->elements[i]; array->num_elements--; }

23 Array ADT Implementation (Cont.) void Array_sort(Array_T array, int (*compare)(void *datap1, void *datap2)) { int i, j; for (i = 0; i num_elements; i++) { for (j = i+1; j num_elements; j++) { if ((*compare)(array->elements[i], array->elements[j]) > 0) { void *swap = array->elements[i]; array->elements[i] = array->elements[j]; array->elements[j] = swap; }

24 Summary Module supporting operations on single data structure  Interface declares operations, not data structure  Interface provides access to simple, complete set of operations  Interface provides flexibility and extensibility Trick is providing functionality AND generality  Take advantage of features of programming language –void pointers –function pointers Advantages  Provide complete set of commonly used functions (re-use)  Implementation is hidden from client (encapsulation)  Can use for multiple types (polymorphism)