You are on page 1of 54

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6. Pointers, Structs, and Arrays 1. Juli 2011

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 1 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Outline

Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 2 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Recapitulation
What is an enum? How is it encoded? What is a for loop? What is a declaration and what is a denition? What is a namespace for? What is a header le and how do we use it? What is an enum? What happens at the end of a scope? What is the difference between call-by-value and call-by-reference? Why is there a range for all primitive variables in C?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 3 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.1. Pointers
Memory
We have talked a lot about the

mapping from variables to addresses. However, we have never analysed the real addresses.

21: 22; 23; 24; 25; 26; 27; 28:

The memory is enumerated using an

20

// int a

integer.
Pointers are variables that hold the

memory number (address) instead of a value.


/ / holds a f l o a t i n g p o i n t / / number double a ; int a; / / h o l d s address o f a f l o a t i n g / / p o i n t number int b;

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 4 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

We Have Already Used Pointers Before


: C/C++ only supports call-by-value. Call-by-reference is not a language concept.

v o i d f o o ( i n t & a ) { / / a c t u a l l y , C / C++ does n o t s u p p o r t t h i s } ... i n t a = 20; foo ( a ) ;

v o i d f o o ( i n t a ) { / / address now i s copied ( c a l l byv a l u e ) / / work on address o f a , n o t on a d i r e c t l y } ... i n t a = 20; f o o ( / address o f a / ) ;

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 5 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pointers And Addresses


The * operator declares a pointer. int a; i n t p ;

The & operator returns the address of a variable (address operator or reference

operator).
p = &a ;

The * operator makes an operation act on the location an pointers points to

instead of the pointer itself (dereferencing operator.


a += 1 0 ; ( p ) += 1 0 ;

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 6 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pointers and the Memory


Memory

int a; a = 20;
// int a // pointer p

21: 22; 23; 24; 25; 26; 27; 28:

20 22

int *p; p = &a; a++; p++; (*p)++; *p++; // try this at home

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 7 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Exercise

void foo ( i n t & a ) { a +=1; } i n t main ( ) { i n t a = 20; foo ( a ) ; std : : cout < < a; ... }

Rewrite exactly this code without a return statement and without the reference operator.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 8 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Solution
void foo ( i n t a ) { ( a ) + = 1 ; / / i n d i r e c t memory access } i n t main ( ) { i n t a = 2 0 ; / / d i r e c t memory access f o o (&a ) ; std : : cout < < a; ... }

Theres three modications. Analyse the call-by-value for the pointer. Which solution is the better/nicer solution?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 9 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

When to Use Pointers


void foo ( i n t a ) { (a ) + + ; . .. a ++; / / That c o u l d n o t have happened w i t h r e f e r e n c e s }

Pointers are difcult to handle (lots of syntactic overhead). We know how to do it, but do collaborators know? Avoid it whenever possible. Use C++ references instead.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 10 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pointer Syntax
The pointer operator binds to the right neighbour.
int a; i n t b1 ; i n t b2 ; i n t b3 ; i n t c1 , c2 ; i n t c3 , c4 ; i n t c5 , c6 ; i n t c7 , c8 ; i n t c9 ; c7 = c8 ; c7 = c8 ; c7 = c8 ; c7 = c8 ;

By the way, often people write int* p=0; to make the pointer point to nothing. However, also int* p = 20; would be ne (and for almost 100 percent is a bug).

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 11 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pointers and Scopes


i n t p = &a ; f o r ( i n t i =0; i <2; i ++) { i n t a = 2 i ; p = &a ; std : : cout < < a < < std : : endl ; std : : cout < < p < < std : : endl } std : : cout < < a < < s t d : : e n d l ; / / does t h i s work? std : : cout < < p < < s t d : : e n d l ; / / does t h i s work?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 12 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pointers and Scopes


i n t p = &a ; f o r ( i n t i =0; i <2; i ++) { i n t a = 2 i ; p = &a ; std : : cout < < a < < std : : endl ; std : : cout < < p < < std : : endl } std : : cout < < a < < s t d : : e n d l ; / / does t h i s work? std : : cout < < p < < s t d : : e n d l ; / / does t h i s work?

With pointers, we can violate the end-of-scope rules, i.e. we can access variables that do not exist anymore. This is the principle of all these buffer overrun malware.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 12 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.2. Dynamic Memory Allocation Switching Off the Lifecycle Management


double p ; p = new double ; / / now , p p o i n t s t o an e x i s t i n g new v a r i a b l e p = 2 0 ; delete p ; p = 3 0 ; / / now v a r i a b l e i s f r e e d , b u t p s t i l l p o i n t s / / to t h i s variable .

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 13 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Two Memory Leaks


double p ; f o r ( i n t i =0; i <20; i ++) { p = new double ; } delete p ;

f o r ( i n t i =0; i <20; i ++) { double p = new double ; }

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 14 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Two Memory Leaks


double p ; f o r ( i n t i =0; i <20; i ++) { p = new double ; } delete p ;

f o r ( i n t i =0; i <20; i ++) { double p = new double ; }

The upper operation creates 20 doubles on the heap, but it destroys only one double in the end. Consequently, the remaining 19 doubles are lost for the future program execution. Lets sketch the memory layout! The second one destroys the pointer but not the space where the pointer is pointing to. This is why many applications crash after several hours of execution.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 14 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.3. Structsn-Tuples
/ T h i s r e p r e s e n t s one s t u d e n t i n our o n l i n e system / s t r u c t Student { int number ; double averageGrade ; };

Structs allow us to create user-dened data structures (n-tuples). Once declared, we can use them like built-in types. C/C++ takes care of the memory layout. This is particularly important for arrays of

structs.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 15 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Declaration and Denition


/ / T e l l s c o m p i l e r t h a t something / / l i k e a StudentID does e x i s t s t r u c t StudentID ; / T h i s r e p r e s e n t s one s t u d e n t i n our o n l i n e system / s t r u c t Student { int number ; double averageGrade ; StudentID i d ; };

For pointers (and references), it is sufcient to tell the compiler that the type does

exist (declaration).
The declaration is needed for recursive denitions of structs. The declaration is needed for more the composition of structs.

Well rst analyse struct composition.


6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 16 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Struct Composition (Attributes)


/ / T e l l s c o m p i l e r t h a t something / / l i k e a StudentID does e x i s t s t r u c t StudentID { int photoNumber ; bool isWinterTerm ; }; / T h i s r e p r e s e n t s one s t u d e n t i n our o n l i n e system / s t r u c t Student { int number ; double averageGrade ; StudentID i d ; / / i t i s n t a p o i n t e r anymore };

Take a sheet of paper and sketch the memory layout for an instance of Student if the id is a pointer and if it is not a pointer.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 17 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Memory

Memory

21: 22; 23; 24; 25; 26; 27; 28:

40 true

// photoNo // winter term

1234 3.4 22

// number // average grade // pointer

24; 25; 26; 27; 28; 29; 30: 31:

1234 3.4 40 true

// number // average grade // photoNo // winter term

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 18 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Structs Referencing Structs

struct IntegerEntry { int value ; I n t e g e r E n t r y next ; };

Take a sheet of paper and sketch the memory layout for an instance of IntegerEntry referencing another instance of IntegerEntry. What could be the reasoning behind such a data structure?
6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 19 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Memory

21: 22; 23; 24; 25; 26; 27; 28:

40 26

// value // next

23 0

// value // next

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 20 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Accessing the Elements of a Struct


/ / T e l l s c o m p i l e r t h a t something l i k e a StudentID does e x i s t struct IntegerEntry { int value ; I n t e g e r E n t r y next ; }; ... I n t e g e r E n t r y myEntry ; myEntry . v a l u e = 2 0 ; myEntry . n e x t = 0 ; I n t e g e r E n t r y p E n t r y = new I n t e g e r E n t r y ; pEntry >v a l u e = 2 0 ; pEntry >n e x t = 0 ; delete pEntry ;

The dot gives access to sub-elds. The -> operator gives access to sub-elds of pointers. Structs can be used with new as well.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 21 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

The Single Linked List


/ / T e l l s c o m p i l e r t h a t something l i k e a StudentID does e x i s t struct IntegerEntry { int value ; I n t e g e r E n t r y next ; }; void p r i n t L i s t ( IntegerEntry f i r s t E n t r y ) { while ( f i r s t E n t r y !=0) { std : : cout < < firstEntry >v a l u e < < ; firstEntry = firstEntry >n e x t ; } } v o i d append ( I n t e g e r E n t r y f i r s t E n t r y , i n t v a l u e ) { while ( f i r s t E n t r y >n e x t ! = 0 ) { firstEntry = firstEntry >n e x t ; } I n t e g e r E n t r y newEntry = new I n t e g e r E n t r y ; firstEntry >n e x t = newEntry ; newEntry >n e x t = 0 ; newEntry >v a l u e = v a l u e ; }

Can you rewrite append() recursively?


6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 22 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Remove Element Operation

Play around with the list and create a

list [2, 4, 6, 8].


Write a remove operation that accepts

an integer k and removes the kth entry from the list.


Invoke it with remove(2). Print the result to the terminal. It

should return [2, 4, 8].

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 23 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

An Excursus on Lists and Complexitythe big-O notation


f O(nk ) Doesnt grow faster than nk .

Faster or slower refers to the leading term of the runtime polynomial. Constants or polynomials of lower order are not considered. Often, one writes = or says is of instead of is contained in. What does this mean for our list? What is the n there?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 24 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

An Excursus on Lists and Complexitythe big-O notation


f O(nk ) Doesnt grow faster than nk .

Faster or slower refers to the leading term of the runtime polynomial. Constants or polynomials of lower order are not considered. Often, one writes = or says is of instead of is contained in. What does this mean for our list? What is the n there? Study the list in terms of n list entries. If we remove the rst element, this is a xed number of operations (O (1)). If we append an element, our while loop has to run over all n element before we

can append an element (O(n)).


If we search for an element, we have to study each element exactly once (O (n)). What could we do to make the append operation run faster?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 24 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.4. Arrays
Application example: At the university, we wanna keep track of four grades a student did throughout his Masters studies.
double double double double ... / Takes grades , computes t h e average , and r e t u r n s t h i s v a l u e . / double computeAverage ( c o n s t double& g1 , c o n s t double& g2 , . . . ) { double r e s u l t = g1+g2+g3+g4 ; r e s u l t /= 4 . 0 ; return result ; } analysis1 ; analysis2 ; linearAlgebra ; stochastics ;

Is this impractical, if we wanna store more than four values.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 25 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Array Declaration
Memory

21: 22; 23; 24; 25; 26; 27; 28:

// grade[0] // grade[1] // grade[2] // grade[3]

double grade [ 4 ] ; ...

22

// grade (pointer)

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 26 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Array Access
Memory

double grade [ 4 ] ; ...

21: 22; 23; 24; 25; 26; 27; 28:

// grade[0] // grade[1] // grade[2] // grade[3]

grade [ 0 ] grade [ 2 ] grade [ 3 ] grade [ 1 ]

= = = =

1.3; 3.3; 1.0; 4.0;

22

// grade (pointer)

Depending on the context, [] either denes the size of an array (denition) or gives access to individual entries of an array (access).

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 27 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Arrays & Pointers


double grade [ 4 ] ; grade [ 0 ] = 1 . 3 ; grade [ 2 ] = 3 . 3 ; grade [ 3 ] = 1 . 0 ; grade [ 1 ] = 4 . 0 ; double p = grade ; i f ( grade [ 0 ] = = p ) ... i f ( grade [ 1 ] = = ( p + 1 ) ) . . .

/ / always t r u e / / always t r u e

An array variable is basically a pointer to the rst element of the array. An array element access internally implies pointer arithmetics and dereferencing. Again, we thus have to range checks (size of array) at hand at all.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 28 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Grades RevisitedWe need a range variable


/ Takes grades , computes t h e average , and r e t u r n s t h i s value . / double computeAverage ( double grade , int numberOfGrades ) { double r e s u l t = 0 . 0 ; for ( i n t i =0; i <numberOfGrades ; i ++ ) { ... } double s c a l e = numberOfGrades ; r e s u l t /= scale ; return result ; } ... double grade [ 4 ] ;

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 29 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Array Arguments
double computeAverage ( double grade [ ] , i n t numberOfGrades ) { ... } double computeAverage ( c o n s t double grade [ ] , i n t numberOfGrades ) { ... }

This time, the user is not allowed to modify any entry of grade.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 30 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Pitfalls
i n t gradesBSc , gradesMSc [ 5 ] ; gradesMSc [ 5 ] = 2 . 3 ; gradesMSc [ 3 ] + + ; i n t p0 = gradesMSc ; i n t p1 = &gradesMSc [ 0 ] ; i n t p2 = &gradesMSc [ 1 ] ; gradesMSc ++; / / t h a t does n o t work p2 ++; / / arrrgh

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 31 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Dynamic Arrays
double grades = new double [ 4 5 ] ; d e l e t e [ ] grades ;

We can create arrays on the heap. Size might be a variable, too. Corresponding delete has to be a delete[]. delete without brackets just deletes

the rst value.


If we omit delete, we will get a memory leak. If we use the array after delete or before new, it points to garbage (remember:

grades is only a pointer).

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 32 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Array As Return Functions


double createThreeRandomGrades ( ) { double r e s u l t [ 3 ] ; result [0] = 1.3; result [1] = 2.7; result [2] = 1.0; return result ; }

double createThreeRandomGrades ( ) { double r e s u l t = new double [ 3 ] ; result [0] = 1.3; result [1] = 2.7; result [2] = 1.0; return result ; }

At the end of the scope, the pointer is destroyed always. Arrays on the heap are not destroyed. This is called a factory mechanism. Someone else invoking the function has to delete the array.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 33 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Multidimensional Arrays
double m a t r i x [ 4 ] [ 4 ] ; f o r ( i n t i =0; i <4; i ++) { f o r ( i n t j =0; j <4; j ++) { m a t r i x [ i ] [ j ] = i == j ? 1 . 0 : 0 . 0 ; } } matrix [ 2 ] [ 1 ] = 1.0; matrix [12] = 1.0;

What is the semantics of the for loop? Multidimensional arrays basically are at arrays. C/C++ uses row-major format (different to FORTRAN).

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 34 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Arrays of Structs
s t r u c t Person { int age ; double w e i g h t ; };

Person Person p ++;

couple [ 2 ] ; p = couple ;

C/C++ takes care of the memory padding. It stores the entries in the memory in the following order: couple[0].age,

couple[0].weight, couple[1].age, couple[1].weight.


The increment sets the pointer to the subsequent age address.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 35 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Outlook C/C++ Arrays vs. FORTRAN


FORTRAN is claimed to be the language for linear algebra as it is faster. FORTRAN does not provide pointers and dynamic data structures. Consequently, compiler can keep track of who has access where. Consequently, compiler can optimise aggressively (it tries to keep book of all

possible values an array could haveside-effect!).


So, it is all a matter of exclusivity and the const operator.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 36 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.5. Sorting

How can we sort an array with n entries?

or: Yes We Can (watch a movie)

http://www.youtube.com/watch?v=k4RRi ntQc8

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 37 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Bubble Sort
void so rt ( int entries [ ] , c o n s t i n t & numberOfEntries ) { bool sorted = t r u e ; while ( sorted ) { sorted = false ; for ( i n t i =0; i <numberOfEntries 1; i ++ ) { i f ( e n t r i e s [ i ]> e n t r i e s [ i + 1 ] ) { ... sorted = true ; } } } }

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 38 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Complexity of Bubble Sort


Idea of bubble sort: Run over all elements in the list. Compare two subsequent elements whether they are in the correct order. Swap

them if necessary.
If a swap still had been necessary, run over list again. How expensive is the sorting?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 39 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Complexity of Bubble Sort


Idea of bubble sort: Run over all elements in the list. Compare two subsequent elements whether they are in the correct order. Swap

them if necessary.
If a swap still had been necessary, run over list again. How expensive is the sorting? The number of comparisons is a good metric. So, let n be the number of elements

in our list.
At most (worst case), well need n runs over the list. In the average case, well need n/2 runs over the list. In each run, we have to do n 1 comparisons. Overall, the complexity is O (n2 ). More intelligent (but more complex) sorting algorithms need only O (n log n)

comparisons.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 39 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.6. Strings
C has no string concept. C++ has a nice string concept. C has chars. And C has arrays. Thus, C has arrays of chars. And C has a mapping of numbers to chars.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 40 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

CodesThe ASCII Code

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 41 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Termination Codes for Arrays


Memory

21: 22; 23; 24; 25; 26; 27; 28: 29: 30:
6. Pointers, Structs, and Arrays

Lets have the following mapping:

24 12 71 71 14 0

0 Reserved (termination) 12 a 14 o 24 H 71 l

22

// s
page 42 of 50

Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Strings as Arrays
char s [ 6 ] ; s [ 0 ] = H ; s [ 1 ] = a ; s [ 2 ] = l ; s [ 3 ] = l ; s [ 4 ] = o ; s [ 5 ] = 0 ;

Lets have the following mapping: 0 Reserved (termination) 12 a 14 o 24 H 71 l

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 43 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Strings are Arrays


char s [ 6 ] ; s [ 0 ] = H ; s [ 1 ] = a ; s [ 2 ] = l ; s [ 3 ] = l ; s [ 4 ] = o ; s [ 5 ] = 0 ; char myString = H a l l o ;

We dont want to pass an integer with each string. Thus, C appends a 0 as last

character.
Thus, the array has one element more than the string has chars. Pascal follows a different variant.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 44 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Operations on Strings
Memory

21: 22; 23; 24; 25; 26; 27; 28: 29: 30:
6. Pointers, Structs, and Arrays

24 12 71 71 14 0

Write a function length that takes a string and counts the number of entries. This number then is returned.

22

// s
page 45 of 50

Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Length Operation
i n t l e n g t h ( c o n s t char [ ] s ) { i n t length = 0; while ( s [ length ]==0) { l e n g t h ++; } return length ; } char myString = H a l l o ; i n t l e n g t h O f M y S t r i n g = l e n g t h ( myString ) ;

What is copied here (call-by-value)! What happens, if we write char a n o t h e r S t r i n g = myString ;

can we then call length for both strings?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 46 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Copying Strings

char myString = T h i s i s a t e s t ; char myCopy = myString ; d e l e t e [ ] myString ; l e n g t h ( myString )

What happens if we execute this

code?
Write an operation that copies a string.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 47 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

6.7. Trees

Remember our single linked list (for

double values). Imagine we wanna hold this list sorted all the time.
What would an insert operation look

like?
What is the (average) runtime of insert

in terms of elements?
How could we reduce this runime to

O(logn)?

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 48 of 50

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

A list with three entries

struct ListEntry { double v a l u e ; ListEntry smallerEntry ; ListEntry biggerEntry ; };

Code the data structure from above,

and
create a list with three values

{0.4, 1.2, 22} (in this order) as follows:


Create list for 0.4 (with two null

pointers).
Create a list element for 1.2 and

6. Pointers, Structs, and Arrays

append it to 0.4. The append function checks whether it is bigger or equal to its current value. It is not, so it is appended to smallerEntry.
page 49 of 50

Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl

Pointers

Dynamic Memory Allocation

Structsn-Tuples

Arrays

Sorting

Strings

Trees

Trees

The example we implemented is a

0.4 -1.2 12

binary tree, as each node has up to two children.


The average depth of this tree is

O(logn).

22 66.6

If we search for an element (as we

have to do if we insert), the search consequently also is in O(logn).


Theres hundreds of variants for trees

with different properties.


Tree algorithms and recursive code go

hand in hand.

6. Pointers, Structs, and Arrays Einfuhrung in die ProgrammierungIntroduction to C/C++, Tobias Weinzierl page 50 of 50

You might also like