1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f...

54
Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees 6. Pointers, Structs, and Arrays 1. Juli 2011 6. Pointers, Structs, and Arrays Einf ¨ uhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 1 of 50

Transcript of 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f...

Page 1: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

6. Pointers, Structs, and Arrays

1. Juli 2011

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 1 of 50

Page 2: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Outline

• Recapitulation

• Pointers

• Dynamic Memory Allocation

• Structs

• Arrays

• Bubble Sort

• Strings

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 2 of 50

Page 3: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 definition?

• What is a namespace for?

• What is a header file 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 3 of 50

Page 4: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

—6.1. Pointers—

Memory

21:22; 20 // int a23; 24; 25; 26;27; 28:

• We have talked a lot about themapping from variables to addresses.However, we have never analysed thereal addresses.

• The memory is enumerated using aninteger.

• Pointers are variables that hold thememory number (address) instead ofa value.

/ / holds a f l o a t i n g po in t/ / number double a ;i n t a ;/ / holds address o f a f l o a t i n g/ / po i n t numberi n t ∗ b ;

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 4 of 50

Page 5: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

We Have Already Used Pointers Before

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

vo id foo ( i n t & a ) { / / a c t u a l l y , C/C++ does not suppor t t h i s}

. . .i n t a = 20;foo ( a ) ;

vo id foo ( i n t ∗ a ) { / / address now i s copied ( c a l l−by−value )/ / work on address o f a , not on a d i r e c t l y

}

. . .i n t a = 20;foo ( /∗∗ address o f a ∗ / ) ;

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 5 of 50

Page 6: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Pointers And Addresses

• The * operator declares a pointer.

i n t a ;i n t ∗p ;

• The & operator returns the address of a variable (address operator or referenceoperator).

p = &a ;

• The * operator makes an operation act on the location an pointers points toinstead of the pointer itself (dereferencing operator.

a += 10;(∗p ) += 10;

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 6 of 50

Page 7: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Pointers and the Memory

Memory

21:22; 20 // int a23; 24; 22 // pointer p 25; 26;27; 28:

int a;a = 20;

int *p;p = &a;

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 7 of 50

Page 8: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Exercise

vo id foo ( i n t & a ) {a+=1;

}

i n t main ( ) {i n t a = 20;foo ( a ) ;s td : : cout << a ;. . .

}

Rewrite exactly this code without a return

statement and without the reference opera-tor.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 8 of 50

Page 9: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Solution

vo id 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 = 20; / / d i r e c t memory accessfoo (&a ) ;s td : : cout << a ;. . .

}

• There’s three modifications.• Analyse the call-by-value for the pointer.• Which solution is the better/nicer solution?

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 9 of 50

Page 10: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

When to Use Pointers

vo id foo ( i n t ∗ a ) {(∗a )++;. . .a++; / / That could not have happened wi th re ferences

}

• Pointers are difficult 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 10 of 50

Page 11: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Pointer Syntax

The pointer operator binds to the right neighbour.

i n t 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 fine (and for almost 100 percent is a bug).

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 11 of 50

Page 12: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 ;

s td : : cout << a << std : : endl ;s td : : cout << ∗p << std : : endl

}s td : : cout << a << s td : : endl ; / / does t h i s work?s td : : cout << ∗p << s td : : endl ; / / does t h i s work?

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 12 of 50

Page 13: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 ;

s td : : cout << a << std : : endl ;s td : : cout << ∗p << std : : endl

}s td : : cout << a << s td : : endl ; / / does t h i s work?s td : : cout << ∗p << s td : : endl ; / / does t h i s work?

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 12 of 50

Page 14: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

—6.2. Dynamic Memory Allocation—

Switching Off the Lifecycle Management

double ∗p ;

p = new double ; / / now , p po in t s to an e x i s t i n g new v a r i a b l e

∗p = 20;

de le te p ; / / now v a r i a b l e i s f reed , but p s t i l l po in t s/ / to t h i s v a r i a b l e .

∗p = 30;

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 13 of 50

Page 15: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Two Memory Leaks

double ∗p ;

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

}

de le te 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 inthe end. Consequently, the remaining 19 doubles are lost for the future programexecution. Let’s sketch the memory layout! The second one destroys the pointer but notthe space where the pointer is pointing to. This is why many applications crash afterseveral hours of execution.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 14 of 50

Page 16: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Two Memory Leaks

double ∗p ;

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

}

de le te 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 inthe end. Consequently, the remaining 19 doubles are lost for the future programexecution. Let’s sketch the memory layout! The second one destroys the pointer but notthe space where the pointer is pointing to. This is why many applications crash afterseveral hours of execution.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 14 of 50

Page 17: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

—6.3. Structs—n-Tuples—

/∗∗∗ This represents one student i n our on l i ne system∗ /

s t r u c t Student {i n t number ;double averageGrade ;

} ;

• Structs allow us to create user-defined 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 ofstructs.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 15 of 50

Page 18: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Declaration and Definition

/ / T e l l s compi ler t h a t something/ / l i k e a StudentID does e x i s ts t r u c t StudentID ;

/∗∗∗ This represents one student∗ i n our on l i ne system∗ /

s t r u c t Student {i n t number ;double averageGrade ;StudentID∗ i d ;

} ;

• For pointers (and references), it is sufficient to tell the compiler that the type doesexist (declaration).

• The declaration is needed for recursive definitions of structs.

• The declaration is needed for more the composition of structs.

We’ll first analyse struct composition.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 16 of 50

Page 19: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Struct Composition (Attributes)

/ / T e l l s compi ler t h a t something/ / l i k e a StudentID does e x i s ts t r u c t StudentID {

i n t photoNumber ;bool isWinterTerm ;

} ;

/∗∗∗ This represents one student∗ i n our on l i ne system∗ /

s t r u c t Student {i n t number ;double averageGrade ;StudentID

i d ; / / i t i sn ’ 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 17 of 50

Page 20: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Memory

21:22; 40 // photoNo23; true // winter term 24; 25; 26; 1234 // number27; 3.4 // average grade28: 22 // pointer

Memory

24; 25; 26; 1234 // number27; 3.4 // average grade28; 40 // photoNo29; true // winter term 30:31:

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 18 of 50

Page 21: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Structs Referencing Structs

s t r u c t I n tege rEn t r y {i n t value ;I n tege rEn t r y∗ next ;

} ;

Take a sheet of paper and sketch the memory layout for an instance of IntegerEntryreferencing another instance of IntegerEntry. What could be the reasoning behind sucha data structure?

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 19 of 50

Page 22: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Memory

21:22; 40 // value23; 26 // next 24; 25; 26; 23 // value27; 0 // next28:

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 20 of 50

Page 23: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Accessing the Elements of a Struct

/ / T e l l s compi ler t h a t something l i k e a StudentID does e x i s ts t r u c t I n tege rEn t r y {

i n t value ;I n tege rEn t r y∗ next ;

} ;

. . .I n tege rEn t r y myEntry ;myEntry . value = 20;myEntry . next = 0 ;

I n tege rEn t r y∗ pEntry = new In tege rEn t r y ;pEntry−>value = 20;pEntry−>next = 0 ;de le te pEntry ;

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 21 of 50

Page 24: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

The Single Linked List

/ / T e l l s compi ler t h a t something l i k e a StudentID does e x i s ts t r u c t I n tege rEn t r y {

i n t value ;I n tege rEn t r y∗ next ;

} ;

vo id p r i n t L i s t ( I n tege rEn t r y∗ f i r s t E n t r y ) {whi le ( f i r s t E n t r y !=0 ) {

s td : : cout << f i r s t E n t r y−>value << ” ” ;f i r s t E n t r y = f i r s t E n t r y−>next ;

}}

vo id append ( In tege rEn t r y∗ f i r s t E n t r y , i n t value ) {whi le ( f i r s t E n t r y−>next !=0 ) {

f i r s t E n t r y = f i r s t E n t r y−>next ;}I n tege rEn t r y∗ newEntry = new In tege rEn t r y ;f i r s t E n t r y−>next = newEntry ;newEntry−>next = 0 ;newEntry−>value = value ;

}

Can you rewrite append() recursively?

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 22 of 50

Page 25: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Remove Element Operation

• Play around with the list and create alist [2, 4, 6, 8].

• Write a remove operation that acceptsan integer k and removes the kth entryfrom 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 23 of 50

Page 26: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

An Excursus on Lists and Complexity—the big-O notation

f ∈ O(nk ) Doesn’t 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 first element, this is a fixed 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 24 of 50

Page 27: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

An Excursus on Lists and Complexity—the big-O notation

f ∈ O(nk ) Doesn’t 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 first element, this is a fixed 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 24 of 50

Page 28: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

—6.4. Arrays—Application example: At the university, we wanna keep track of four grades a studentdid throughout his Master’s studies.

double ana lys is1 ;double ana lys is2 ;double l i nea rA lgeb ra ;double s tochas t i c s ;

. . .

/∗∗∗ Takes grades , computes the average , and re tu rns t h i s value .∗ /

double computeAverage ( const double& g1 , const double& g2 , . . . ) {double r e s u l t = g1+g2+g3+g4 ;r e s u l t /= 4 . 0 ;r e t u r n r e s u l t ;

}

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 25 of 50

Page 29: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Array Declaration

Memory

21:22; // grade[0]23; // grade[1]24; // grade[2] 25; // grade[3]26;27; 28: 22 // grade (pointer)

double grade [ 4 ] ;

. . .

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 26 of 50

Page 30: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Array Access

Memory

21:22; // grade[0]23; // grade[1]24; // grade[2] 25; // grade[3]26;27; 28: 22 // grade (pointer)

double grade [ 4 ] ;

. . .

grade [ 0 ] = 1 . 3 ;grade [ 2 ] = 3 . 3 ;grade [ 3 ] = 1 . 0 ;grade [ 1 ] = 4 . 0 ;

Depending on the context, [] either definesthe size of an array (definition) or gives ac-cess to individual entries of an array (ac-cess).

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 27 of 50

Page 31: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 ) . . . / / always t ruei f ( grade [1 ]==∗ ( p +1) ) . . . / / always t rue

• An array variable is basically a pointer to the first 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 28 of 50

Page 32: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Grades Revisited—We need a range variable

/∗∗∗ Takes grades , computes the∗ average , and re tu rns t h i s∗ value .∗ /

double computeAverage (double∗ grade ,i n t numberOfGrades

) {double r e s u l t = 0 . 0 ;f o r (

i n t i =0; i<numberOfGrades ; i ++) {

. . .}double scale = numberOfGrades ;r e s u l t /= scale ;r e t u r n r e s u l t ;

}

. . .double grade [ 4 ] ;

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 29 of 50

Page 33: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Array Arguments

double computeAverage ( double grade [ ] , i n t numberOfGrades ) {. . .

}

double computeAverage ( const 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 30 of 50

Page 34: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 not workp2++; / / a r r rgh

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 31 of 50

Page 35: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Dynamic Arrays

double∗ grades = new double [ 4 5 ] ;

de le te [ ] 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 deletesthe first 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 32 of 50

Page 36: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Array As Return Functions

double∗ createThreeRandomGrades ( ) {double r e s u l t [ 3 ] ;r e s u l t [ 0 ] = 1 . 3 ; r e s u l t [ 1 ] = 2 . 7 ; r e s u l t [ 2 ] = 1 . 0 ;r e t u r n r e s u l t ;

}

double∗ createThreeRandomGrades ( ) {double∗ r e s u l t = new double [ 3 ] ;r e s u l t [ 0 ] = 1 . 3 ; r e s u l t [ 1 ] = 2 . 7 ; r e s u l t [ 2 ] = 1 . 0 ;r e t u r n r e s u l t ;

}

• 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 33 of 50

Page 37: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Multidimensional Arrays

double mat 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 ++) {

mat r i x [ i ] [ j ] = i == j ? 1.0 : 0 . 0 ;}

}mat r i x [ 2 ] [ 1 ] = 1 . 0 ;mat r i x [ 1 2 ] = 1 . 0 ;

• What is the semantics of the for loop?

• Multidimensional arrays basically are flat arrays.

• C/C++ uses row-major format (different to FORTRAN).

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 34 of 50

Page 38: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Arrays of Structs

s t r u c t Person {i n t age ;double weight ;

} ;

Person couple [ 2 ] ;Person∗ p = couple ;p++;

• 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 35 of 50

Page 39: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 allpossible values an array could have—side-effect!).

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

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 36 of 50

Page 40: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 37 of 50

Page 41: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Bubble Sort

vo id s o r t (i n t e n t r i e s [ ] ,const i n t & numberOfEntr ies

) {bool sor ted = t rue ;wh i le ( sor ted ) {

sor ted = f a l s e ;f o r (

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 ] ) {

. . .sor ted = t rue ;

}}

}}

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 38 of 50

Page 42: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 elementsin our list.

• At most (worst case), we’ll need n runs over the list.• In the average case, we’ll 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 39 of 50

Page 43: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 elementsin our list.

• At most (worst case), we’ll need n runs over the list.• In the average case, we’ll 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 39 of 50

Page 44: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 40 of 50

Page 45: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Codes—The ASCII Code

Code 0 is a reserved value and does not represent a value.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 41 of 50

Page 46: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Termination Codes for Arrays

Memory

21:22; 2423; 1224; 71 25; 7126; 1427; 028:29: 30: 22 // s

Lets have the following mapping:

0 Reserved (termination)

12 a

14 o

24 H

71 l

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 42 of 50

Page 47: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 43 of 50

Page 48: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-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∗ myStr ing = ” Ha l lo ” ;

• We don’t want to pass an integer with each string. Thus, C appends a 0 as lastcharacter.

• 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 Programmierung—Introduction to C/C++, Tobias Weinzierl page 44 of 50

Page 49: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Operations on Strings

Memory

21:22; 2423; 1224; 71 25; 7126; 1427; 028:29: 30: 22 // s

Write a function length that takes a stringand counts the number of entries. This num-ber then is returned.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 45 of 50

Page 50: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Length Operation

i n t leng th ( const char [ ] s ) {i n t leng th = 0;wh i le ( s [ leng th ]==0) {

l eng th ++;}r e t u r n leng th ;

}

char∗ myStr ing = ” Ha l lo ” ;i n t lengthOfMyStr ing = leng th ( myStr ing ) ;

• What is copied here (call-by-value)!

• What happens, if we write

char∗ ano therS t r ing = myStr ing ;

can we then call length for both strings?

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 46 of 50

Page 51: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Copying Strings

char∗ myStr ing = ” This i s a t e s t ” ;char∗ myCopy = myStr ing ;de le te [ ] myStr ing ;leng th ( myStr ing )

• What happens if we execute thiscode?

• Write an operation that copies a string.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 47 of 50

Page 52: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

—6.7. Trees—

• Remember our single linked list (fordouble values). Imagine we wannahold this list sorted all the time.

• What would an insert operation looklike?

• What is the (average) runtime of insertin terms of elements?

• How could we reduce this runime toO(logn)?

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 48 of 50

Page 53: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

A list with three entries

s t r u c t L i s t E n t r y {double value ;L i s t E n t r y∗ sma l le rEn t ry ;L i s t E n t r y∗ b iggerEnt ry ;

} ;

• Code the data structure from above,and

• create a list with three values{0.4,−1.2, 22} (in this order) asfollows:

• Create list for 0.4 (with two nullpointers).

• Create a list element for −1.2 andappend it to 0.4. The append functionchecks whether it is bigger or equal toits current value. It is not, so it isappended to smallerEntry.6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 49 of 50

Page 54: 1. Juli 2011 - TUM · 2011-07-08 · An Excursus on Lists and Complexity—the big-O notation f 2O(nk) Doesn’t grow faster than nk. Faster or slower refers to the leading term of

Pointers Dynamic Memory Allocation Structs—n-Tuples Arrays Sorting Strings Trees

Trees

0.4

-1.2 22

12 66.6

• The example we implemented is abinary tree, as each node has up totwo children.

• The average depth of this tree isO(logn).

• If we search for an element (as wehave to do if we insert), the searchconsequently also is in O(logn).

• There’s hundreds of variants for treeswith different properties.

• Tree algorithms and recursive code gohand in hand.

6. Pointers, Structs, and Arrays

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 50 of 50