Procedural Programming & Fundamentals of Programming Lecture 3 - Summer Semester 2018 & Joachim Zumbrägel What we know so far... Data type serves to organize data (in the memory), its possible values, allowed changes and use of storage. (Function) procedure is a self-contained block of instructions (a subpart of the program) making use of data that have specific types. Variables and (function) procedures must be declared to be known or visible within their scope and defined to allocate memory to them for storing values during their lifetime. (Function) procedures have parameters, which correspond to their local variables. Formal parameters of a procedure declare these local variables, while actual parameters initiate them by values given on a procedure call. 2 1
Passing parameters requires knowing which values to use? When calling a procedure, it needs to know which values to use for replacing a formal by an actual parameter. There are different kinds of method how to replace a formal by an actual parameter, for example we will discuss Call-by-value Call-by-reference Procedure: a block of instructions / program statements Procedure call: starts execution of a procedure Caller: the one who starts execution of procedure Callee: is the called procedure PROCEDURE Example(x:integer, y:integer) y = y + 1; x = x * 2; ENDPROCEDURE DECLARE a,b:integer; Example(...):void; START a = 7; b = 4; CALL Example with a and a CALL Example with b and b END 3 Call-by-value (1/2) In call-by-value, a local copy of the passed variables is made and passed into the (function) procedure. The caller's copy cannot be modified. If the (function) procedure is able to assign values to its parameters, only its local copy is assigned that is, anything passed into a call is unchanged in the caller's scope when the (function) procedure returns. Data structures such as arrays are copied too, which can be undesired especially if a huge amount of data must be coped with. 4 2
Call-by-value (2/2) PROCEDURE Example(x:integer, y:integer) x = x * 2; y = y + 1; ENDPROCEDURE Variable Value of variable a 7 7 7 b 4 4 4 x 7 14 4 8 y 7 8 4 5 DECLARE a,b:integer; Example(...):void; START a = 7; b = 4; CALL Example with a and a CALL Example with b and b END END 5 Call-by-reference (1/2) In Call-by-reference, a (function) procedure receives an implicit reference to a variable (its memory address) used as argument, rather than a copy of its value. This typically means that the function can modify the variable used as argument (the caller's copy). Changes remain after end of procedure. Call-by-reference can therefore be used to provide an additional channel of communication between the caller and the callee, which may introduce subtle bugs. 6 3
Call by reference (2/2) PROCEDURE Example(x:AdrOf(integer), y:adrof(integer)) (ContentOfAdrIn)x = (ContentOfAdrIn)x * 2; (ContentOfAdrIn)y = (ContentOfAdrIn)y + 1; ENDPROCEDURE Variable Value of variable DECLARE a,b:integer; Example(...):void; START a = 7; b = 4; CALL Example with adr a and adr a CALL Example with adr b and adr b END a 7 14 15 15 15 b 4 4 8 9 9 x adr a adr a adr b adr b y adr a adr a adr b adr b 7 Pointers A pointer is a variable that stores a reference to a variable. Its value is the address or location of a variable. In C, a memory address is called a pointer. C lets you access memory locations directly. A pointer is a data type, DECLARE b:integer; a:(integer)pointer; b = 4; a = (AdrOf)b; which is usually 2, 4, or 8 bytes, depending upon machine architecture. Variable Value of variable Comments a adr b a is a pointer variable to an integer value at address of b b 4 b is an integer variable 8 4
Benefits of using of pointers Pointers are very flexible in their use. Sometimes pointers are the only way to express a computation. Pointers usually lead to more efficient code. Pointers allow for changing values passed by a (function) procedure call. Dynamic memory management is based on using pointers. 9 Declaration of pointers (1/4) Just like variables, pointers must be declared before using them. The keyword at the beginning (int, char and so on) declares the type of variable that the pointer will point to. An asterisk (*) is placed before the variable name. Read pointer declarations from right to left. type *s; a pointer to an object of type type int *p; a pointer to an integer double *q; a pointer to a double char **r; a pointer to a pointer to a char 10 5
Declaration of pointers (2/4) const int *p; p is a pointer to an integer constant. i.e., pointer can change, thing it points to cannot. Variable Value of variable Comments p adr k (or) adr m p is a pointer variable to addresses of const int k 4 k is a constant integer variable of value 4 m 9 m is a constant integer variable of value 9 11 Declaration of pointers (3/4) int *const q; q is a constant pointer to an integer variable. i.e., pointer cannot change, thing it points to can! Variable Value of variable Comments q adr v q is a constant pointer variable to address v v 4 (or) 9 v is an integer variable 12 6
Declaration of pointers (4/4) const int *const r; r is a constant pointer to an integer constant Variable Value of variable Comments r adr z adr z q is a constant pointer variable to address z z 123 123 z is a constant integer variable of value 123 13 Addresses pointed to a reference The ampersand (&) operator gives the address of a variable. integer a = 123; a is a variable of type integer, whose value is 123 integer *x; x is declared as a pointer variable to an integer x = &a; x is assigned with the address of variable a, x references or points to variable a Variable Value of variable Comments a 123 123 a is a variable of type integer x - adr a x is a pointer variable, which refers or points to variable a 14 7
Dereference The asterisk (*) operator allows to access the value of a variable, which is referenced by pointer. This is known as to dereference a pointer. integer a = 123; integer variable a is assigned with the value 123 integer *y; pointer variable y is declared for referencing variables of type integer y =&a; the value of pointer variable y is assigned with the address of variable a integer b = *y; Dereferencing pointer variable y is used to assign the value of y s pointee (which is variable a) to variable b *y = 666; Dereferencing pointer variable y is used to assigne the value 666 to its pointee a. Variable Value of variable y adr a adr a adr a a 123 123 123 666 b 123 123 15 Dereference (2/2) The "dereference" operation follows a pointer's reference to get the value of its pointee. The only restriction is that the pointer must have a pointee for the dereference to access. Almost all bugs in pointer code involve violating that one restriction. 16 8
The NULL Pointer is a special pointer value. encodes the idea of "points to nothing. in a graphical representation it is usually drawn as a diagonal line between the corners of the pointer variable's box. Example: int *numptr = NULL; The C language uses the symbol NULL for this purpose. In C, NULL is equal to the integer constant 0. Deferencing a NULL pointer leads to an exception or unpredictable behavior of the program. 17 Pointer operations Dereference: asterisk (*) operator enables access to value of pointed variable (pointee). Increment/Decrement: ++/-- operator on pointer changes adress to subsequent or preceding variable in memory Address Assignment: to pointers should be done with care. References to invalid addresses should be avoided to prevent unpredictable program behavior. Compare: with other pointers or NULL. 18 9
Dangling Pointers when points to released storage (1/2) void main(void){ integer x = 88; integer *y = NULL; Y=exampleFunc();... int* ExampleFunc(){ integer localx = 42; return (&localx); } x = *y;... Variable Value of variable } x 88 88 88 88??? y NULL NULL NULL adr localx adr localx localx 42 42 19 Dangling Pointers when points to released storage (2/2) ExampleFunc(...) returns a pointer to an address of a local variable: return (&localx) => y refers to local variable After leaving ExampleFunc(...) the pointer is used again: x = *y; Problem: local variable localx does not exist anymore after leaving ExampleFunction(...). Its storage has been released. This is named 'dangling pointer. If storage is reused again is left to chance. The program has an error, but it still can work (sometimes). Double check your damn pointers! 20 10
Pointers and Memory Data program ti.uni due.de Prof. Dr. Ing. Axel Hunger Procedural Programming Overview Data Types Data Types Simple / Scalar Access / Pointer Structured / / Primitive / Dynamic Composite coming next ordinal real array record/struct set/union file integer, bool, char text/string Enumerations 22 11
What we know so far... Data is stored in binary form in memory. Data Types specified for data in a program give meaning (value) to the content of a storage cell. Pointer is a type of data representing a memory address. Pointers are flexible, which comes with pros and cons for memory management and corresponding data access. Next we discuss data structures... 23 An Overview of Data Types predefined simple access / dynamic Data Types derived composite Scalar Pointer Structured ordinal real array struct union file integer, bool, char record set String text Enumerations 24 12
Two Classifications of Data Types (1/3) Pre-defined data types (int, char, double, float, void) Derived data types (array, string, structure) Programmer-defined data types Structure Union Enumeration 25 Pre-defined data types (2/3) void used to denote the type with no values int used to denote an integer type char used to denote a character type float, double used to denote a floating point number Int *, float *, char * used to denote a pointer type 26 13
Derived Data Types (3/3) Array a finite sequence (or table) of variables of the same data type String an array of character variables Structure a collection of related variables of the same and/or different data types The structure is often called a record. Variables in the record are called members or fields. 27 Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to organize these data bundles in a way that is convenient to program the handling of these data by algorithms and execute the program efficiently. 28 14
Array Array (1/2) A collection of objects of the same type stored contiguously in memory under one name May be type of any kind of variable May even be collection of arrays! For ease of access to any member of array For passing to functions as a group The most common data structure used to store collections of elements 30 15
Array (2/2) Convenient to declare and provide the handy [ ] syntax to access any element by its index number in most languages. May be used wherever a variable of the same type may be used in an expression (including arguments) on left side of assignment Array Index the expression between the square brackets 31 Array Examples (1/2) int A[10] An array of ten integers A[0], A[1],, A[9] double B[20] An array of twenty long floating point numbers B[0], B[1],, B[19] Arrays of structs, unions, pointers, etc., are also allowed Array indexes always start at zero in C 32 16
Array Examples (2/2) int C[] An array of an unknown number of integers (allowable in a parameter of a function) C[0], C[1],, C[max-1] int D[10][20] An array of ten rows, each of which is an array of twenty integers D[0][0], D[0][1],, D[1][0], D[1][1],, D[9][19] 33 Pointers and Arrays (1/2) Arrays and pointers are closely related in C int A[10]; int *p; Type of A is int p = A is a legal assignments *p refers to A[0] *(p + n) refers to A[n] p = &A[5]; is the same as p = A + 5; 34 17
Pointers and Arrays (2/2) double A[10]; vs. double *A; Only difference: double A[10] sets aside ten units of memory, each large enough to hold a double double *A sets aside one pointer-sized unit of memory You are expected to come up with the memory elsewhere! Note: all pointer variables are the same size in any given machine architecture Regardless of what types they point to 35 Caution! It is the programmer s responsibility to avoid indexing off the end of an array Likely to corrupt data May cause a segmentation fault Could expose system to a security hole! C does NOT check array bounds I.e., whether index points to an element within the array Might be high (beyond the end) or negative (before the array starts) 36 18
Attributes of and operations on arrays Number of dimensions Vector: one-dimensional array Matrix: two-dimensional array Multi-dimensional array (more than two dimensions) Fixed size: Range of each dimension Homogeneous: Data type of each component Component selection: accessing a component via its index Component assignment: assigning a new value to a selected component 37 Mapping of real thing to array Array of the first ten prime numbers int prime_no [10] Access the prime number 17: prime_no [6] Index Value 0 2 1 3 2 5 3 7 4 11 5 13 6 17 7 19 8 23 9 29 38 19
Two-Dimensional Arrays (1/2) A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns 39 Two-Dimensional Arrays (2/2) 40 20
Physically, in one block of memory The entire array is allocated as one block of memory Each element in the array gets its own space Any element can be accessed fast and convenient directly using the [ ] syntax 41 Mapping of real thing to Two-Dimensional Array Row-column and x-y coordinates for a pixel location in an image pixel [2] [3] int pixel [5] [5] 42 21
Physically, in one block of memory int pixel [5] [5] pixel [2] [3] Row 0 Row 1 Row 2 Row 3 Row 4 43 Disadvantages of Arrays 1) The size of the array is fixed. The most convenient thing for programmers to do is to allocate arrays which seem "large enough" (e.g. 100). Although convenient, this strategy has two disadvantages: a) Most of the time there are just 20 or 30 elements in the array and 70% of the space in the array really is wasted. b) If the program ever needs to process more than 100 scores, the code breaks. 44 22
Strings Strings There is no string type in C Instead, strings are implemented as arrays of characters enclosed in double-quotes terminated by NULL character ( \0') "Hello same as char str[ ] = { 'H', 'e', 'l', 'l', 'o', \0' } 46 23
String implemented as array of characters terminated by NULL character ( \0') enclosed in double-quotes Example: char str[6] = "Hello same as char str[6] = {'H','e','l','l','o', \0'} str H e l l o \0 [0] [1] [2] [3] [4] [5] 47 String Handling Functions (1/2) implemented in libraries The string library string.h (on some systems strings.h) is useful for working with strings. Provides functions like: strcpy, strcat, strcmp, strlen, strcoll, etc. 48 24
String Handling Functions (2/2) strcpy used to copy a string and can be used like this strcpy(destination, source) strcmp used to compare two strings and can be used like this: strcmp(str1, str2) strcat concatenates a string onto the end of the other string strlen returns the length of a string. (All characters before the null termination 49 25