Outline Review Functions Pointers –Function calls –Array Pointers –Pointer Arrays Data Structures and dynamic Memory Function Pointers –quicksort example.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Programming in C Chapter 10 Structures and Unions
C Language.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
Programming Languages and Paradigms The C Programming Language.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Pointers in C Rohit Khokher
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 10.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Topic R3 – Review for the Final Exam. CISC 105 – Review for the Final Exam Exam Date & Time and Exam Format The final exam is 120-minutes, closed- book,
Guide To UNIX Using Linux Third Edition
Pointers Applications
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 8 Arrays and Strings
Introduction to the C Programming Language Michael Griffiths
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Fundamentals of C and C++ Programming Simple data structures Pointers.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Review 1 List Data Structure List operations List Implementation Array Linked List.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C LANGUAGE Characteristics of C · Small size
1D Arrays and Random Numbers Artem A. Lenskiy, PhD May 26, 2014.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
‘C’ Programming Structures and Commands
Functions, Part 2 of 2 Topics Functions That Return a Value
Programming Languages and Paradigms
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Programming Paradigms
C Basics.
Lecture2.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Computer Science 210 Computer Organization
C Structures, Unions, Bit Manipulations and Enumerations
Derived types.
Programming Languages and Paradigms
Presentation transcript:

Outline Review Functions Pointers –Function calls –Array Pointers –Pointer Arrays Data Structures and dynamic Memory Function Pointers –quicksort example

Functions Functions enable grouping of commonly used code into a reusable and compact unit. In programs containing many functions main should be implemented as a group of calls to functions undertaking the bulk of the work Become familiar with rich collections of functions in the ANSI C standard library Using functions from ANSI standard library increases portability

Standard Library Functions HeaderDescription Functions for standard input and output Floating point size limits Contains integral size limits of system Functions for converting numbers to text and text to numbers, memory allocation, random numbers, other utility functions Math library functions String processing functions Common definitions of types used by C

Functions available with the library math.h FunctionReturns sqrt(x)Square root exp(x)Exponential function log(x)Natural logarithm (base e) log10(x)Logarithm (base 10) fabs(x)Absolute value pow(x,y)X raised to the power of y sin(x)Trignometric sine (x in radians) cos(x)Trignometric cosine (x in radians) tan(x)Trignometric tangent (x in radians) atan(x)Arctangent of x (returned value is in radians)

Using Functions Include the header file for the required library using the preprocessor directive –#include –Note no semi colon after this Variables defined in functions are local variables Functions have a list of parameters –Means of communicating information between functions Functions can return values printf and scanf good examples of function calls Use the –lm option to compile an application using math library functions e.g. –pgcc myprog.c –o myprog -lm

User Defined Functions Format of a function definition Return-value-type function-name(parameter-list) { declarations statements } A return value of type void indicates a function does not Return a value.

Functions: return Return control to point from which function called 3 Ways to return –Function does not return a result (void) control is returned when function right brace } is reached. –Execute the statement return; –If the statement returns a value the following statement must be executed return expression;

Function Prototypes Tells compiler –type of data returned by function –Number and types of parameters received by a function Enable compiler to validate function calls Function prototype for a RollDice function –int RollDice(int iPlayer); –Terminated with ; –Placed after pre-processor declarations and before function definitions

Using Functions Declare function using prototype Define source code for function Call the function See program functions.c for an example of function declaration, definition, usage

Header Files Standard libraries have header files containing function prototypes for all functions in that library Programmer can create custom header files –Should end in.h e.g. myfunctionlib.h Programmer function prototypes declared using the pre processor directive –#include “myfunctionlib.h”

Demonstration Build and run the example function1.c Add more calls to the blorf() function in the main pprogram Build and run function2.c Note this avoids the use of the function prototype Move the soup function after the main function compile and run what happens? Add a prototype and build and run again

Pointers and Arrays Pointers are a powerful feature of C which have remained from times when low level assembly language programming was more popular. Used for managing –Arrays –Strings –Structures –Complex data types e.g. stacks, linked lists, queues, trees

Variable Declaration A variable is an area of memory that has been given a name. The variable declaration –float f1; –is command to allocate an area of memory for a float variable type with the name f1. The statement –f1=3.141 –is a command to assign the value to the area of memory named f1.

What is a Pointer Pointers are variables that contain memory addresses as their values. Pointer declared using the indirection or de- referencing operator *. Example –float *f1ptr; f1ptr is pointer variable and it is the memory location of a float variable

Pointer Example The redirection operator returns the address of a variable & applied to f1 returns the address of f1 float f1; float *f1ptr; /* Declare a pointer variable to an integer*/ f1=3.141; f1ptr=&f1; /*f1ptr is set to the address of f1*/

f1ptr3.141 f f1 f1 directly references a variable of value f1ptr indirectly references a variable of value Pointer Variables

Using the * and & operators: /*1*/ Declare an integer /*2*/ Declare a pointer /*3*/ Assign a value to the pointer variable /*4*/ Use the pointer in a function (dereference the value) Compile and run the example pointers.c int some_var; /*1*/ int *ptr_to_some_var; /*2*/ ptr_to_some_var = &some_var; /*3*/ printf ("%d\n\n", *ptr_to_some_var); /*4*/

Function Calls Call by value –Copy of variable passed to function –If that variable is modified within the function then upon return from the function since only the copy has been modified, the actual variable is not modified Call by reference –Pass the address of a variable (i.e. a pointer) to a function –The variable pointed to can be modified within that function

Call By Value Example finval=FuncByValue(finval); The FuncFyValue function float FuncByValue(float fval) { return fval*fval; }

Call By Reference Example FuncByReference(&finref), Use & to pass the address of a variable to the function; The FuncByReference function Value of the referenced variable passed to the function is modified after returning from the function. void FuncByReference(float *fvalptr) { *fvalptr = *fvalptr * *fvalptr; }

Arrays Initialisation int iarray[5]={1,2,3,4,5}; Or… initialise elements individually Note first element is referenced using 0 –iarray[0]=1; –…….. –iarray[4]=5;

Further Examples of function calls Putting it all together –Function calls –Simple array examples Numerical Method Examples –Numerical differentiation –Numerical Integration

Multidimensional Array The declaration for a multi dimensional array is made as follows: –Type variable[size1][size2]; To access or assign an element to an element of a multidimensional array we use the statement: –variable[index1][index2]=avalue;

Matrix Initialisation example Alternatively the bracket initialisation method can be used, for example the integer matrix[2][4] can be initialised as follows: int matrix[2][4] { {1,2,3,4}, {10,20,30,40} };

Arrays are Pointers The array variable is a pointer whose value is the address of the first element of the array. For a one dimensional array access a value using the following pointer notation: int ielement= *(iarray+1); This assignment increments the array pointer to the second element in the array (the first element is always index 0) uses the * operator to dereference the pointer

Pointer Arrays A string is a pointer to an array of characters An array of strings is an array of pointers Multidimensional array is essentially an array of pointer arrays.

Memory Leaks TAKE VERY SPECIAL CARE IN USE OF POINTERS AND MANAGEMENT OF ARRAYS A common problem when using arrays is that the program might run off the end of the array particularly when using pointer arithmetic. When passing an array to a function it is good practice to pass the size of that array making the function more general.

Data Types and Structures Features for representing data and aggregations of different data types. –structures, – type definitions, –enumerations and –unions.

Data Structures Arrays and structures are similar –pointers to an area of memory that –aggregates a collection of data. Array – All of the elements are of the same type and are numbered. Structure –Each element or field has its own name and data type.

Format of a data structure struct structure-name { field-type field-name; /*description*/ ……. } variable-name;

Declaring structures and Accessing Fields struct structure-name variable-name; A pointer to a structure –struct structure-name *ptr-variable-name; Accessing a field in a structure –variable-name.field-name For a pointer to a structure a field is accessed using the indirection operator -> –ptr-variable-name->field-name

Structure Example struct node { char *name; char *processor; int num_procs; };

Declaring and Initialising Structures struct node n1; struct node *n1ptr; n1.name="Titania"; n1.processor ="Ultra Sparc III Cu"; n1.num_procs = 80; n1ptr = &n1;

Accessing Structure data Direct access printf("The node %s has %d %s processors\n", n1.name, n1.num_procs, n1.processor); Access using a pointer printf("The node %s has %d %s processors\n", n1ptr->name, n1ptr->num_procs, n1ptr->processor); Dereferencing a pointer printf("The node %s has %d %s processors\n", (*n1ptr).name, (*n1ptr).num_procs, (*n1ptr).processor);

Type definitions –typedef float vec[3]; Defines an array of 3 float variables a particle position may then be defined using: –vec particlepos; Defined structure types –typedef struct structure-name mystruct; –mystruct mystructvar;

Enumerations enum enum-name {tag-1, tag-2, ….} variable-name; enum months {JAN=1, FEB, MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC}; Same as int JAN=1; int FEB=2;.. int DEC=12;

Using an Enumeration enum months month; for(month=JAN; month<=DEC; month++) statement;

Declaring and Using an Enumeration int main () { enum compass_direction { north, east, south, west }; enum compass_direction my_direction; my_direction = west; return 0; }

Dynamic Memory Allocation Allocate Memory –malloc –calloc Free memory –Free Size of memory used by variabletype –sizeof

Using malloc struct node *newPtr; newPtr = (struct node *)malloc(sizeof(struct node)); The (struct node *) before the malloc statement – used to recast the pointer returned by malloc from (void *) to (struct node *).

Free me! free(newPtr);

Reserving memory for an array int n=10; struct node *newPtr; newPtr = (struct node *)calloc(n, sizeof(struct node)); Avoid memory leaks Free the memory! free(newPtr);

Pointers to Functions Pointer to function –Address of the function in memory –Starting address of the code Quick sort function has prototype (see 2 slides later) –int (*fncompare)(const void *, const void *) –fncompare is function pointer –Tells quicksort to expect pointer to a function receiving 2 pointers to void Note without the brackets around *fncompare the declaration becomes a declaration of a function

Declaration of Function Using a Pointer to a Function Declare mysortfunc as –mysortfunc(int *data, int size, int (*compare)(void *, void *)) Call mysortfunc in the following way –mysortfunc(data,size,ascending) –mysortfunc(data,size,descending) Ascending and descending are functions declared as –Int ascending(void *a, void *b) –Int descending(void *a, void *b)

Array of pointers to functions Declare functions –void function1(int); –void function2(int); –void function3(int); void (*f[3])(int)={function1,function2, function3}; Called as follows –(*f[choice])(myintergerinput); –Choice and myintegerinput are both integers

Application of Function Pointers Numerical recipes –E.g. function which is dependent on a differential which has yet to be defined Quick sort function see next slides Make C object oriented –Include pointers to data methods in struct data types…. See later!

Using the quick sort function Implementation of quick sort algorithm Qsort function in Features –Pointer to void * –Pointer to a function

Syntax for qsort function implementation of the quicksort algorithm to sort the num elements of an array pointed by base –each element has the specified width in bytes –method used to compare each pair of elements is provided by the caller to this function with fncompare parameter (a function called one or more times during the sort process). void qsort ( void * base, size_t num, size_t width, int (*fncompare)(const void *, const void *) );

Example Using qsort /* qsort example */ #include int values[] = { 40, 10, 100, 90, 20, 25 }; int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main () { int * pItem; int n; qsort (values, 6, sizeof(int), compare); for (n=0; n<6; n++) { printf ("%d ",values[n]); } return 0; }

Examples Compile and run the following programs –Program array.c initialising and using arrays with pointers –Program bubblesort.c is a bubble sort example, using call by reference to manipulate data passed into a function –Program arrayref.c uses pointer notation to manipulate arrays –Modify the bubblesort program to use the qsort routine

Practical Examples Compile and run the following programs –Numerical Differentiation 2 and four point methods –Numerical Integration Trapezium method Simpsons rule (includes lagrange interpolation function)