Algorithms and data structures 7.11.2015. Protected by http://creativecommons.org/licenses/by-nc-sa/3.0/hr/ Creative Commons  You are free to: share — copy and redistribute the material in any medium.

Download Report

Transcript Algorithms and data structures 7.11.2015. Protected by http://creativecommons.org/licenses/by-nc-sa/3.0/hr/ Creative Commons  You are free to: share — copy and redistribute the material in any medium.

Algorithms and data structures
7.11.2015.
Protected by http://creativecommons.org/licenses/by-nc-sa/3.0/hr/
Creative Commons

You are free to:
share — copy and redistribute the material in any medium or format
 adapt — remix, transform, and build upon the material


Under the following terms:



Attribution — You must give appropriate credit, provide a link to the license, and
indicate if changes were made. You may do so in any reasonable manner, but
not in any way that suggests the licensor endorses you or your use.
NonCommercial — You may not use the material for commercial purposes.
ShareAlike — If you remix, transform, or build upon the material, you must
distribute your contributions under the same license as the original.
No additional restrictions — You may not apply legal terms or technological
measures that legally restrict others from doing anything the license permits.
Notices:
You do not have to comply with the license for elements of the material in the public domain or where your use is
permitted by an applicable exception or limitation.
No warranties are given. The license may not give you all of the permissions necessary for your intended use. For
example, other rights such as publicity, privacy, or moral rights may limit how you use the material.
Text copied from http://creativecommons.org/licenses/by-nc-sa/3.0/
Algorithms and data structures, FER
7.11.2015.
2 / 24
Repetition of some topics in
Programming
Pointers
Files
Dynamic memory allocation
7.11.2015.
Pointers
What shall print this programming sequence?
Pokazivač (Pointer) How much memory is allocated?

#include <stdio.h>
int main () {
int a = 4;
int *b;
What data type is *b?
What data type is b?
b = &a;
What would happen if this statement were omitted?
*b = 8;
printf ("%d %d\n", a, *b);
return 0;
}
Algorithms and data structures, FER
7.11.2015.
4 / 24
Solution

What would happen if we omit the statement b = &a; ?
As the pointer b points to an undefined address before any value is
assigned to it, it might come to an attempt to write the value of 8 to an
address reserved for storing some other variables or parts of the code, what
may cause unexpected behaviour or run time error due to unauthorised
access to a memory part.
 The value of a pointer must always be initialised before use.
 The program in MS Visual C++ terminates with error due to an uninitialized
variable
AritmetikaPokazivaca (PointerArithmetics)

Why is it necessary to specify the data type to be pointed at?
Algorithms and data structures, FER
7.11.2015.
5 / 24
Exchange of data with a function - call by value
void exchange(int three, int seven) { // call by value
int aux;
aux = three;
three = seven;
seven = aux;
}
int main () {
int three=3, seven=7;
exchange(three, seven);
return 0;
}
 KomunikacijaSFunkcijama(CommunicationWithFunctions)
Algorithms and data structures, FER
7.11.2015.
6 / 24
Exchange of data with a function - call by reference
void exchange (int *three, int *seven) { //call by reference
int aux;
aux = *three;
*three = *seven;
*seven = aux;
}
int main () {
int three=3, seven=7;
exchange (&three, &seven);
return 0;
}
 KomunikacijaSFunkcijama(CommunicationWithFunctions)
Algorithms and data structures, FER
7.11.2015.
7 / 24
Exchange of data with a function - local exchange of addresses
void exchange (int *three, int *seven) {
int *aux;
// local exchange of addresses
aux = three;
three = seven;
seven = aux;
}
int main () {
int three=3, seven=7;
exchange (&three, &seven);
return 0;
}
 KomunikacijaSFunkcijama(CommunicationWithFunctions)
Algorithms and data structures, FER
7.11.2015.
8 / 24
Allocation and release of memory

In definition of an array, memory is assigned for the maximum expected
number of array elements:
How many bytes are assigned?
int array[1000];

However, most often a significantly lesser number of array elements are used
Another frequent error:
scanf("%d", &n);
int array[n];

A better approach is to ask for an exactly required amount of memory:





malloc
realloc
free
#include <malloc.h>
Algorithms and data structures, FER
7.11.2015.
9 / 24
Memory allocation
#include <malloc.h>
void *malloc (size_t size);


Allocates a memory block of size bytes and returns the pointer to
that block
If a block of the required size cannot be allocated, it returns NULL
value for pointer.
void *

Pointer to an undefined data type (pointer to “anything”)
Without loss of data it can be transformed to any other pointer type
 PrimjerZaMalloc(ExampleForMalloc)

Algorithms and data structures, FER
7.11.2015.
10 / 24
Resizing of allocated memory
#include <malloc.h>
void *realloc (void *block, size_t size);



If the already allocated memory block can be extended to size, it
is extended
If there is not enough contiguous space, old block’s contents copy is
written to a new location where there is enough contiguous space
for size bytes
If nowhere in the memory size bytes of free contiguous space can
be found, NULL value is returned

if block contains NULL value, the function acts like malloc
Algorithms and data structures, FER
7.11.2015.
11 / 24
Releasing of memory
#include <malloc.h>
void free (void *block);


Releases the memory block pointed at by the pointer block
The pointer block may only result from previous calls of functions
malloc or realloc
Algorithms and data structures, FER
7.11.2015.
12 / 24
Example of memory allocation

A sequential formatted file array is stored on disk where each row contains a single integer.
Read the file contents into the memory as an one-dimensional array.
 Form a squared matrix in the computer memory, where the elements of the first row are
equal to the elements of input one-dimensional array, while the elements of other rows are
equal to squares, cubes and further higher powers of the first row.
 The formed matrix should be written to disk on a sequential unformatted file narray so
that the first number is the count of rows or columns (int), and then the matrix elements
row-wise.
E.g. The file array should be entered into the one-dimensional array and then the matrix
formed.


1
2
3
Algorithms and data structures, FER
1
1
1
2 3
4 9
8 27
7.11.2015.
13 / 24
Example of memory allocation: the result of execution

Input data:
3
2
4
8
5
Writing on the screen:
3
9
27
81
243
2
4
8
16
32
4
16
64
256
1024
8
64
512
4096
32768
5
25
125
625
3125
 MallocMatrica(MallocMatrix)
Algorithms and data structures, FER
7.11.2015.
14 / 24
Algorithms and data structures, FER
7.11.2015.
15 / 24
Possible numerical errors
for(n=0;n<i;n++)
for(j=0;j<i;j++)
p[n*i+j]=(int)pow(p[j],n+1);
If multiplication is used instead, there are no truncation errors:
for (j = 0; j < n; j++) {
r(0,j) = p[j];
for (i = 1; i < n; i++) {
r(i,j) = r(i-1,j) * r(0,j);
}
}
Algorithms and data structures, FER
7.11.2015.
16 / 24
Arrays of pointers

Declaration
char *p[3];
allocates in memory an array of 3 elements with members
p[0], p[1] and p[2] of type char *
what can be visualised as
?
?
?
Algorithms and data structures, FER
7.11.2015.
17 / 24
Example

Write a program to copy the contents of a sequential formatted file
into another file row-wise, but backwards, from the last row towards
the first one. File names should be specified in the command line.

Solution with memory reallocation
Realloc
0
11
23
34
46
Algorithms and data structures, FER
first row\r\n
second row\r\n
third row\r\n
fourth row\r\n
fifth row\r\n
7.11.2015.
18 / 24
Exercises
Pointers
Arrays
Records
Files
7.11.2015.
Pointers

Write a function that would return the date of birth in the form
DD.MM.YYYY from the entered personal ID. The memory for the
resulting string must be allocated using malloc.
 DatumJMBG(DateID)
Algorithms and data structures, FER
7.11.2015.
20 / 24
Arrays - 1


From the sequential formatted file InputForTwodimensinalArray.txt read
the number of rows and columns of the integer array and then
sequentially read the values.
Print the members of two-dimensional array, together with indices of
the two-dimensional and the index of the corresponding onedimensional array, and its contents.
 DvodimenzionalnoPolje(TwodimensionalArray)
Algorithms and data structures, FER
7.11.2015.
21 / 24
Arrays - 2

Write a function to calculate the sum of positive elements of a twodimensional array and illustrate the function call from the main
program.
Reminder: two-dimensional array is transferred to a function like onedimensional. It is stored row-wise so that the element p[i,j] can be accessed
as p [i*maxstup + j].
 SumaUPolju(SumInArray)

Algorithms and data structures, FER
7.11.2015.
22 / 24
Records and files

From the sequential formatted file students.txt a direct unformatted file
students.dat should be formed where the record structure is:
struct record {
int ID; // 3 digits
char name [40+1];
char gender[1+1];
}
Write a function to fetch the data for a student with a given ID and than to
delete the record from the file. Student’s ID corresponds to the sequential
record number. An empty record contains the ID equal 0.
 DohvatiBrisi(FetchDelete)

What happens if retrieval is attempted for a negative ID?
Algorithms and data structures, FER
7.11.2015.
23 / 24
Record and files

In the Taxation office in a sequential unformatted file taxes.dat there are
taxation data for a population. Essential data are:




ID (13+1 digit),
Name and family name (40+1 char),
Overall declared income (float) and
Amount of taxes left to pay (float).
At the beginning of the file there is a number of type long containing the count
of records in the file. Write the program containing the following parts:


Function to transfer the file contents into a dynamically allocated struct array
Function to locate the citizen who has to pay the maximum tax.
 Porez(Tax)
Algorithms and data structures, FER
7.11.2015.
24 / 24