29.05.2018
1
Procedural Programming & Fundamentals of ProgrammingLecture 3 - Summer Semester 2018
Prof. Dr.-Ing. Axel Hunger & Joachim Zumbrägel
2
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 totheir local variables.
• Formal parameters of a procedure declare these local variables, while actual parameters initiate them by values given on a procedure call.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
2
3
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
■ 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 procedureProf. Dr.-Ing. Axel Hunger
PROCEDURE Example(x:integer, y:integer)y = y + 1;x = x * 2;ENDPROCEDURE
DECLARE a,b:integer;Example(...):void;
STARTa = 7;b = 4;CALL Example
with a and aCALL Example
with b and bEND
− Call-by-value− Call-by-reference
4
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.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
3
5
Call-by-value (2/2)
Prof. Dr.-Ing. Axel Hunger
PROCEDURE Example(x:integer, y:integer)x = x * 2;y = y + 1;ENDPROCEDURE
DECLARE a,b:integer;Example(...):void;
STARTa = 7;b = 4;CALL Example
with a and aCALL Example
with b and bENDVariable Value of variable
a 7 7 7
b 4 4 4
x ‐ 7 14 ‐ 4 8 ‐
y ‐ 7 8 ‐ 4 5 ‐
with b and bEND
6
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.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
4
7
Call by reference (2/2)
Prof. Dr.-Ing. Axel Hunger
PROCEDURE Example(x:AdrOf(integer), y:AdrOf(integer))
(ContentOfAdrIn)x = (ContentOfAdrIn)x * 2;(ContentOfAdrIn)y = (ContentOfAdrIn)y + 1;ENDPROCEDURE
DECLARE a,b:integer; Example(...):void;
STARTa = 7;b = 4;CALL Examplewith adr a and adr aCALL Example
Variable Value of variable
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 ‐
with adr b and adr bEND
8
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,
which is usually 2, 4, or 8 bytes, depending upon machine architecture.
Prof. Dr.-Ing. Axel Hunger
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
DECLAREb:Integer;a:(Integer)Pointer;b = 4;a = (AdrOf)b;
29.05.2018
5
9
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.
Prof. Dr.-Ing. Axel Hunger
10
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.
Prof. Dr.-Ing. Axel Hunger
type *s; a pointer to an object of type typeint *p; a pointer to an integerdouble *q; a pointer to a doublechar **r; a pointer to a pointer to a char
29.05.2018
6
11
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) adrm 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 ofvalue 9
Prof. Dr.-Ing. Axel Hunger
12
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 toaddress v
v 4 (or) 9 v is an integer variable
Prof. Dr.-Ing. Axel Hunger
29.05.2018
7
13
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 ofvalue 123
Prof. Dr.-Ing. Axel Hunger
14
Addresses pointed to – a reference
• The ampersand (&) operator gives the address of a variable.
Prof. Dr.-Ing. Axel Hunger
Variable Value of variable Comments
a 123 123 a is a variable of type integer
x - adr a x is a pointer variable, which refersor points to variable a
integer a = 123; a is a variable of type integer, whose value is 123integer *x; x is declared as a pointer variable to an integerx = &a; x is assigned with the address of variable a,
x references or points to variable a
29.05.2018
8
15
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.
Variable Value of variable
y ‐ adr a adr a adr aa 123 123 123 666b ‐ ‐ 123 123Prof. Dr.-Ing. Axel Hunger
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 itspointee a.
16
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 pointeefor the dereference to access.
• Almost all bugs in pointer code involve violating that one restriction.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
9
17
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.
Prof. Dr.-Ing. Axel Hunger
18
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.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
10
19
Dangling Pointers – when points to released storage (1/2)
void main(void){
integer x = 88;
integer *y = NULL;
Y=exampleFunc();
...
x = *y;
...
}
Prof. Dr.-Ing. Axel Hunger
Variable Value of variable
x 88 88 88 88 ???y NULL NULL NULL adr localx adr localxlocalx ‐ ‐ 42 42 ‐
int* ExampleFunc(){integer localx = 42;return (&localx);}
20
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!
Prof. Dr.-Ing. Axel Hunger
29.05.2018
11
Procedural Programming
Pointers and Memory
ti.uni‐due.de Prof. Dr.‐Ing. Axel Hunger
Data
program
22
Overview Data Types
Prof. Dr.-Ing. Axel Hunger
Data Types
Simple / Scalar/ Primitive
ordinal
integer, bool, char
Enumerations
real
Access / Pointer/ Dynamic
Structured / Composite
array record/Struct set/union file
text/String
coming next
29.05.2018
12
23
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...
Prof. Dr.-Ing. Axel Hunger
24
An Overview of Data Types
Prof. Dr.-Ing. Axel Hunger
Data Types
Scalar
ordinal
integer, bool, char
Enumerations
real
Pointer Structured
array struct union file
String
„simple“ „access“ / „dynamic“ „composite“
„record“ „set“
„text“
predefined derived
29.05.2018
13
25
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 typesStructureUnionEnumeration
Prof. Dr.-Ing. Axel Hunger
26
Pre-defined data types (2/3)
void – used to denote the type with no values int – used to denote an integer typechar – used to denote a character typefloat, double – used to denote
a floating point numberInt *, float *, char * – used to denote a pointer type
Prof. Dr.-Ing. Axel Hunger
29.05.2018
14
27
Derived Data Types (3/3)
Array – a finite sequence (or table) of variablesof the same data type
String – an array of character variablesStructure – 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.
Prof. Dr.-Ing. Axel Hunger
28
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.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
15
Array
30
Array (1/2)
A collection of objects of the same type stored contiguously in memory under one nameMay be type of any kind of variableMay even be collection of arrays!For ease of access to any member of arrayFor passing to functions as a groupThe most common data structure used to store collections of elements
Prof. Dr.-Ing. Axel Hunger
29.05.2018
16
31
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
Prof. Dr.-Ing. Axel Hunger
32
Array – Examples (1/2)
int A[10]
An array of ten integersA[0], A[1], …, A[9]
double B[20]
An array of twenty long floating point numbersB[0], B[1], …, B[19]
Arrays of structs, unions, pointers, etc., are also allowed
Array indexes always start at zero in C
Prof. Dr.-Ing. Axel Hunger
29.05.2018
17
33
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 integersD[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]
Prof. Dr.-Ing. Axel Hunger
34
Pointers and Arrays (1/2)
• Arrays and pointers are closely related in Cint A[10];int *p;
Type of A is intp = 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;
Prof. Dr.-Ing. Axel Hunger
29.05.2018
18
35
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
Prof. Dr.-Ing. Axel Hunger
36
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)
Prof. Dr.-Ing. Axel Hunger
29.05.2018
19
37
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
Prof. Dr.-Ing. Axel Hunger
38
Mapping of real “thing” to array
Array of the first tenprime numbers
int prime_no [10]
0 21 32 53 74 115 136 177 198 239 29
Index Value
Access the prime number 17:
prime_no [6]
Prof. Dr.-Ing. Axel Hunger
29.05.2018
20
39
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
Prof. Dr.-Ing. Axel Hunger
40
Two-Dimensional Arrays (2/2)
Prof. Dr.-Ing. Axel Hunger
29.05.2018
21
41
Physically, in one block of memory
Prof. Dr.-Ing. Axel Hunger
The entire array is allocated as one block of memoryEach element in the array gets its own spaceAny element can be accessed fast and convenient directly using the [ ] syntax
42
Mapping of real “thing” to Two-Dimensional Array
• Row-column and x-y coordinates for a pixel location in an image
int pixel [5] [5]
pixel [2] [3]
Prof. Dr.-Ing. Axel Hunger
29.05.2018
22
43
Physically, in one block of memory
Row 0 Row 1 Row 2 Row 3 Row 4
pixel [2] [3]
int pixel [5] [5]
Prof. Dr.-Ing. Axel Hunger
44
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.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
23
Strings
46
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' }
Prof. Dr.-Ing. Axel Hunger
29.05.2018
24
47
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'}
H e l l o \0[0] [1] [2] [3] [4] [5]
str
Prof. Dr.-Ing. Axel Hunger
48
String Handling Functions (1/2)
implemented in librariesThe string library string.h (on some systems strings.h) is useful for working with strings.
Provides functions like:strcpy,
strcat,
strcmp,
strlen,
strcoll, etc.
Prof. Dr.-Ing. Axel Hunger
29.05.2018
25
49
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
Prof. Dr.-Ing. Axel Hunger