forked from uva-cs/pdr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-cpp.html
1834 lines (1594 loc) · 51.3 KB
/
01-cpp.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CS 2150: 01-cpp slide set</title>
<meta name="description" content="A set of slides for a course on Program and Data Representation">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="../slides/reveal.js/css/reveal.css">
<link rel="stylesheet" href="../slides/reveal.js/css/theme/black.css" id="theme">
<link rel="stylesheet" href="../slides/css/pdr.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="../slides/reveal.js/lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? '../slides/reveal.js/css/print/pdf.css' : '../slides/reveal.js/css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="../slides/reveal.js/lib/js/html5shiv.js"></script>
<![endif]-->
<script type="text/javascript" src="../slides/js/dhtmlwindow.js"></script>
<script type="text/javascript" src="../slides/js/canvas.js"></script>
<link rel="stylesheet" href="../slides/css/dhtmlwindow.css" type="text/css">
<style>.reveal li { font-size:93%; line-height:120%; }</style>
</head>
<body onload="canvasinit()">
<div id="dhtmlwindowholder"><span style="display:none"></span></div>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section data-markdown><script type="text/template">
# CS 2150
### Program and Data Representation
<center><small><a href="http://www.cs.virginia.edu/~asb">Aaron Bloomfield</a> (aaron@virginia.edu)</small></center>
<center><small><a href="http://@github/uva-cs/pdr">@github</a> | <a href="index.html">↑</a> | <a href="daily-announcements.html?print-pdf"><img class="print" width="20" src="../slides/images/print-icon.png"></a></small></center>
## C++
</script></section>
<section>
<h2>CS 2150 Roadmap</h2>
<table class="wide">
<tr><td colspan="3"><p class="center">Data Representation</p></td><td></td><td colspan="3"><p class="center">Program Representation</p></td></tr>
<tr>
<td class="top"><small> <br> <br>string<br> <br> <br> <br>int x[3]<br> <br> <br> <br>char x<br> <br> <br> <br>0x9cd0f0ad<br> <br> <br> <br>01101011</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/red-double-arrow.png" height="500" alt="vertical red double arrow"></td>
<td class="top"> <br>Objects<br> <br>Arrays<br> <br>Primitive types<br> <br>Addresses<br> <br>bits</td>
<td> </td>
<td class="top"><small> <br> <br>Java code<br> <br> <br>C++ code<br> <br> <br>C code<br> <br> <br>x86 code<br> <br> <br>IBCM<br> <br> <br>hexadecimal</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/green-double-arrow.png" height="500" alt="vertical green double arrow"></td>
<td class="top"> <br>High-level language<br> <br>Low-level language<br> <br>Assembly language<br> <br>Machine code</td>
</tr>
</table>
</section>
<section data-markdown><script type="text/template">
# Contents
[Introduction to C++](#/intro)
[Functions](#/functions)
[Classes](#/classes)
[Rational Example](#/rational)
[Pre-Processor](#/preproc)
[Pointers](#/pointers)
[Dynamic Memory Allocation](#/dynamic)
[References](#/references)
[Parameter Passing](#/parameters)
[Sample (advanced) code](#/advanced)
</script></section>
<section>
<section data-markdown id="intro"><script type="text/template">
# Introduction to C++
</script></section>
<section data-markdown><script type="text/template">
## Why C++ and not Java?
- It's good to learn a second language
- C++ is widely used
- Can be more efficient
- More control
- C++ will let us "get under the hood" more
- Data and program representation in memory
- Memory allocation
</script></section>
<section data-markdown><script type="text/template">
## A brief history lesson
- C was created in 1972 by Dennis Ritchie
- Intended to be terse, quick to write, and efficient
- C++ was created in 1985 by Bjarne Stroustrup
- Added classes while being backwards compatible
- Has pretty terrible syntax!
</script></section>
<section data-markdown><script type="text/template">
## Hello World: Java vs. C++
```java
// Java
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello World!");
}
}
```
```
// C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Differences
- `main()`
- Preprocessor
- `#include`
- `using namespace std;`
- Output
</script></section>
<section data-markdown><script type="text/template">
## main()
- Not a part of any class
- called a *function*
- Must be global
- Must have a return type of int
- By convention, main returns 0
- You must *ALWAYS* return 0 from main()
</script></section>
<section data-markdown><script type="text/template">
## Preprocessor
- Examples
- `#include <iostream> // System file`
- `#include "ListNode.h" // user file`
- What this does
- Compiler inserts the contents of the file in the place where the `#include` statement appears
</script></section>
<section data-markdown><script type="text/template">
## C++ Compilation Process Overview
1. Preprocess source file
- handle \#includes and any other \# statements
2. Compile resulting file
3. Link the resulting files from step 2 (more on this later)
</script></section>
<section>
<h2>using Directive</h2>
<p> </p>
<ul>
<li>Similar to Java's <span class="tt">import</span>
<ul>
<li>Uses a namespace, which is somewhat similar to a Java package</li>
<li>Allows the programmer to not have to type the full namespace name each time</li>
</ul>
</li>
</ul>
<table class="transparent" style="margin-left:0">
<tbody>
<tr>
<td> </td>
<td>
<pre style="margin-left:0"><code data-trim>// C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!"
<< endl;
return 0;
}
</code></pre>
</td>
<td>
<pre><code data-trim>// C++
#include <iostream>
int main() {
std::cout << "Hello World!"
<< std::endl;
return 0;
}
</code></pre>
</td>
</tr>
</tbody>
</table>
</section>
<section data-markdown><script type="text/template">
## I/O
- Basic I/O
```
// use iostream library
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter a value for x: ";
cin >> x;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## C++ Primitive Types
- int
- Can be 16, 32, 64 bits depending on the platform
- float
- double
- char
- C++ generally uses 8 bit ASCII encoding (more on this later)
- bool
</script></section>
<section data-markdown><script type="text/template">
## C++ Operators and Expressions
- if statement
- In C++, the condition can be either `int` or `bool`
- Assume `x` is an `int`
- `if ( x )`
- This is valid!
- `if ( x = 0 )`
- This will *NOT* cause a compiler error in C++!
</script></section>
<section data-markdown><script type="text/template">
## Operators and Expressions
- Loops, same as Java
- while, for, do while, break, continue
- Same syntax as well
</script></section>
<section data-markdown><script type="text/template">
## Compiler choice
- In the past we have used g++
- From GNU's Compiler Collection
- We are now using clang++ (from LLVM)
- It has *MUCH* better error messages
- Consider:
```
#include <iostream>
using namespace std;
int main() {
// note the spelling mistake on the next
// line where 'cout' is spelled 'cotut'
cotut << "Hello World";
return 0;
}
```
</script></section>
<section>
<h2>Error comparison</h2>
<p> </p>
<table class="wide">
<tr><td class="middletrans">g++:</td><td><img width="850" alt="g++ error message" src="images/01-cpp/g++-error-message.png"></td></tr>
<tr><td class="middletrans">clang++:</td><td><img width="850" alt="clang++ error message" src="images/01-cpp/clang++-error-message.png"></td></tr>
</table>
</section>
</section>
<section>
<section data-markdown id="functions"><script type="text/template">
# Functions
</script></section>
<section data-markdown><script type="text/template">
## Functions
- Methods that are not a member of a class
#include <iostream>
using namespace std;
ret_type func_name(int a, int b, ...) {
<function body>
}
int main() {
...
z = func_name(x, y, ...);
...;
return 0;
}
</script></section>
<section>
<h2>Declaring mutually<br>recursive functions</h2>
<p>Source code: <a href="code/01-cpp/evenodd.cpp.html">evenodd.cpp</a> (<a href="code/01-cpp/evenodd.cpp">src</a>)</p>
<table class="transparent">
<tr>
<td> </td>
<td> </td>
<td>
<pre class="fragment"><code data-trim>bool even (int x);</code></pre>
<pre><code data-trim>bool odd (int x) {
if ( x == 0 )
return false;
else
return even (x-1);
}
</code></pre></td>
<td>
<p> </p>
<pre><code data-trim>bool even (int x) {
if ( x == 0 )
return true;
else
return odd (x-1);
}
</code></pre></td>
</tr>
</table>
</section>
<section data-markdown><script type="text/template">
## Function Prototypes
- C++ compiler process files top to bottom
- order of appearance matters without a **function prototype**
- General form of a prototype:
```
ret_type func_name (int a, int b, ...);
```
- In this context, they are also called *forward declarations*
</script></section>
<section data-markdown><script type="text/template">
## Example
Source code: [cpptest.cpp](code/01-cpp/cpptest.cpp.html) ([src](code/01-cpp/cpptest.cpp))
```
#include <iostream>
using namespace std;
int max(int a, int b); // prototype
int main() {
int x=37, y=52;
cout << max(x,y) << endl;
return 0;
}
// actual function implementation
int max(int a, int b) {
return (a>b) ? a : b;
}
```
</script></section>
</section>
<section>
<section data-markdown id="classes"><script type="text/template">
# Classes
</script></section>
<section data-markdown><script type="text/template">
## Java: IntCell.java
Source code: [IntCell.java](code/01-cpp/IntCell.java.html) ([src](code/01-cpp/IntCell.java))
```
public class IntCell {
// default constructor
public IntCell() {
this(0);
}
// one parameter constructor
public IntCell(int initialValue) {
storedValue = initialValue;
}
// accessor member function
public int getValue() {
return storedValue;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Java: IntCell.java
Source code: [IntCell.java](code/01-cpp/IntCell.java.html) ([src](code/01-cpp/IntCell.java))
```
// mutator member function
public void setValue(int val) {
storedValue = val;
}
// private data member
private int storedValue;
// main()
public static void main(String [] args) {
IntCell m1 = new IntCell();
IntCell m2 = new IntCell(37);
System.out.println(m1.getValue() + " " +
m2.getValue());
}
}
```
</script></section>
<section data-markdown><script type="text/template">
## How Would You Translate This<br>Java Source into C++?
- Need 3 files
1. Header file that contains class definition: IntCell.h
2. C++ file that contains class implementation: IntCell.cpp
3. C++ file that contains a main(): TestIntCell.cpp
- Note the separation of interface and implementation!
</script></section>
<section data-markdown><script type="text/template">
## C++ IntCell: TestIntCell.cpp
Source code: [TestIntCell.cpp](code/01-cpp/TestIntCell.cpp.html) ([src](code/01-cpp/TestIntCell.cpp))
```
#include <iostream>
#include "IntCell.h"
using namespace std;
int main( ) {
IntCell m1; // calls the default constructor
IntCell m2( 37 );
cout << m1.getValue( ) << " "
<< m2.getValue( ) << endl;
m1 = m2;
m2.setValue( 40 );
cout << m1.getValue( ) << " "
<< m2.getValue( ) << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## C++ IntCell: IntCell.h
Source code: [IntCell.h](code/01-cpp/IntCell.h.html) ([src](code/01-cpp/IntCell.h))
```
#ifndef INTCELL_H
#define INTCELL_H
class IntCell {
public:
IntCell( int initialValue = 0 );
int getValue( ) const;
void setValue( int val );
private:
int storedValue;
int max(int m) const;
};
#endif
```
</script></section>
<section data-markdown><script type="text/template">
## C++ IntCell: IntCell.cpp
Source code: [IntCell.cpp](code/01-cpp/IntCell.cpp.html) ([src](code/01-cpp/IntCell.cpp))
```
#include "IntCell.h"
using namespace std; // (not really necessary, but...)
IntCell::IntCell( int initialValue ) :
storedValue( initialValue ) {
}
int IntCell::getValue( ) const {
return storedValue;
}
void IntCell::setValue( int val ) {
storedValue = val;
}
int IntCell::max(int m) const {
return (m>storedValue) ? m : storedValue;
}
```
</script></section>
<section data-markdown><script type="text/template">
## C++ IntCell: IntCell.h (again)
Source code: [IntCell.h](code/01-cpp/IntCell.h.html) ([src](code/01-cpp/IntCell.h))
```
#ifndef INTCELL_H
#define INTCELL_H
class IntCell {
public:
IntCell( int initialValue = 0 );
int getValue( ) const;
void setValue( int val );
private:
int storedValue;
int max(int m) const;
};
#endif
```
</script></section>
<section data-markdown><script type="text/template">
## C++ IntCell: TestIntCell.cpp (again)
Source code: [TestIntCell.cpp](code/01-cpp/TestIntCell.cpp.html) ([src](code/01-cpp/TestIntCell.cpp))
```
#include <iostream>
#include "IntCell.h"
using namespace std;
int main( ) {
IntCell m1; // calls the default constructor
IntCell m2( 37 );
cout << m1.getValue( ) << " "
<< m2.getValue( ) << endl;
m1 = m2;
m2.setValue( 40 );
cout << m1.getValue( ) << " "
<< m2.getValue( ) << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Separate Compilation
![Separate compilation](images/01-cpp/separate-compilation.png)
</script></section>
</section>
<section>
<section id="rational" data-markdown><script type="text/template">
# Rational Example
</script></section>
<section data-markdown><script type="text/template">
## The General Conversion Process
1. Create .h file with class definition
- Member function signatures, no implementations
2. Create .cpp file containing member function implementations
3. Create .cpp file containing `main()`
</script></section>
<section data-markdown><script type="text/template">
## Reminders
- int main()
- Input/Output
- `#include <iostream>`
- `using namespace std;`
- `cout << varName << " " << endl;`
- Class syntax
- public and private sections
- semi-colon at the end of class declaration
- ClassName::
</script></section>
<section data-markdown><script type="text/template">
## We'll see why later, but for now...
- Printing
- instead of '+' use '<<' to concatenate items to print
- Remove `this` and `new` from conversion
- Using `#ifndef`, `#define`, and `#endif` in the .h files
</script></section>
<section data-markdown><script type="text/template">
## Rational.h
Source code: [Rational.h](code/01-cpp/Rational.h.html) ([src](code/01-cpp/Rational.h))
```
#ifndef RATIONAL_H
#define RATIONAL_H
class Rational {
public:
Rational(); // default constructor
~Rational(); // destructor
Rational(int numerator, int denominator);
void print() const;
Rational times(Rational b) const;
Rational plus(Rational b) const;
Rational reciprocal() const;
Rational divides(Rational b) const;
private:
int num, den; // the numerator and denominator
static int gcd(int m, int n);
};
#endif
```
</script></section>
<section data-markdown><script type="text/template">
## Rational.cpp, 1 of 2
Source code: [Rational.cpp](code/01-cpp/Rational.cpp.html) ([src](code/01-cpp/Rational.cpp))
```
#include "Rational.h"
#include <iostream>
using namespace std;
// default constructor: initialize to 0/1
Rational::Rational() : num(0), den(1) { }
void Rational::print() const {
if (den == 1)
cout << num << "" << endl;
else
cout << num << "/" << den << endl;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Rational.cpp, 2 of 2
Source code: [Rational.cpp](code/01-cpp/Rational.cpp.html) ([src](code/01-cpp/Rational.cpp))
```
Rational Rational::times(Rational b) const {
return Rational(num * b.num, den * b.den);
}
Rational::Rational(int numerator, int denominator) {
if (denominator == 0)
cout << "Denominator is zero" << endl;
int g = gcd(numerator, denominator);
num = numerator / g;
den = denominator / g;
}
```
</script></section>
<section data-markdown><script type="text/template">
## TestRational.cpp
Source code: [TestRational.cpp](code/01-cpp/TestRational.cpp.html) ([src](code/01-cpp/TestRational.cpp))
```
#include <iostream>
using namespace std;
#include "Rational.h"
int main() {
Rational x, y, z;
// 1/2 + 1/3 = 5/6
x = Rational(1, 2);
y = Rational(1, 3);
z = x.plus(y);
z.print();
// ... other code very much like above
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## .h vs. .cpp?
- C++ naming convention
- .h files are header files
- function prototypes
- class definitions
- macro definitions
- .cpp files are implementation files
- Definitions may only appear in 1 place
- compiler errors: "multiply defined XYZ"
</script></section>
</section>
<section>
<section id="preproc" data-markdown><script type="text/template">
# Pre-processor
</script></section>
<section data-markdown><script type="text/template">
## Preprocessing
- \#include
- Direct copy of file specified to location specified
- In general, only #include .h files.
- \#ifndef
- "if not defined"
- Other preprocessor directives: #ifdef, #if
- \#endif
- Specifies the end of any #if
- \#define
- Defines a macro (direct text replacement)
```
#define TRUE 0
if(TRUE == 0) {...}
#define MY_OBJECT_H
```
</script></section>
<section data-markdown><script type="text/template">
## #define
- Can define a constant
```
#define PI 3.14159
...
area = PI * r * r;
```
- Can just define an identifier
```
#define FOO
#ifdef FOO // is true!
// ...
#endif
#ifndef FOO // is false!
// ...
#endif
```
</script></section>
<section data-markdown><script type="text/template">
## What problems arise?
- odd.h:
```
#include "even.h"
bool odd (int x);
```
- even.h:
```
#include "odd.h"
bool even (int x);
```
</script></section>
<section data-markdown><script type="text/template">
## Preventing #include loops
- odd.h:
```
#ifndef ODD_H
#define ODD_H
#include "even.h"
bool odd (int x);
#endif
```
- even.h:
```
#ifndef EVEN_H
#define EVEN_H
#include "odd.h"
bool even (int x);
#endif
```
</script></section>
</section>
<section>
<section id="pointers" data-markdown><script type="text/template">
# Pointers
</script></section>
<section data-markdown><script type="text/template">
## Pointer Variables
- Stores a memory address of another object
- Can be a primitive type or a class type
</script></section>
<section data-markdown><script type="text/template">
## Examples of Pointers
- `int * x;`
- pointer to `int`
- `char *y;`
- pointer to `char`
- `Rational * rPointer;`
- pointer to `Rational`
</script></section>
<section data-markdown><script type="text/template">
## What Types are These?
- `float * num1;`
- `double num2;`
- `Rational fraction1;`
- `Square * square1;`
- `int num3;`
</script></section>
<section data-markdown><script type="text/template">
## C++ Syntax: *
- Asterisk: *
- In a definition
- defines pointer type
- `int * x;`
- In an expression
- "dereferences"
- evaluates object to which the pointer points
- `*x = 2;`
</script></section>
<section data-markdown><script type="text/template">
## C++ Syntax: &
- Ampersand: &
- In a definition
- defines a reference type (more on this later)
- In an expression
- "address of"
- `x = &y;`
</script></section>
<section>
<h2>Pointer Variables</h2>
<p>Source code: <a href="code/01-cpp/pointers.cpp.html">pointers.cpp</a> (<a href="code/01-cpp/pointers.cpp">src</a>)</p>
<table class="transparent"><tr><td>
<table class="transparent">
<tr><th>Variable</th><th>Address</th><th>Memory</th></tr>
<tr><td><p class="center"><span class="fragment" data-fragment-index="1">x</span></p></td><td>1000</td><td class="border"><p class="center"><span class="fragment" data-fragment-index="4">1</span></p></td></tr>
<tr><td><p class="center"><span class="fragment" data-fragment-index="2">y</span></p></td><td>1008</td><td class="border"><p class="center"><span class="fragment" data-fragment-index="5">5</span></p></td></tr>
<tr><td><p class="center"><span class="fragment" data-fragment-index="3">x_pointer</span></p></td><td>1016</td><td class="border"><p class="center"><span class="fragment" data-fragment-index="6">1000</span></p></td></tr>
<tr><td></td><td>1024</td><td class="border"><p> </p></td></tr>
<tr><td></td><td>1032</td><td class="border" style="border-bottom:medium solid;"><p> </p></td></tr>
</table>
</td><td></td><td>
<pre><code data-trim>int x = 1;
int y = 5;
int * x_pointer = &x;
cout << x_pointer;
cout << *x_pointer;
</code></pre>
</td></tr></table>
<!-- <script type="text/javascript">insertCanvas();</script> -->
</section>
<section>
<h2>x_pointer = &x</h2>
<img class="stretch" alt="Poitner code execution" src="images/01-cpp/pointers-1.png">
</section>
<section data-markdown><script type="text/template">
## Dereferencing and Assigning
Source code: [pointers.cpp](code/01-cpp/pointers.cpp.html) ([src](code/01-cpp/pointers.cpp))
<table class="transparent"><tr><td>
<table class="transparent">
<tr><th>Variable</th><th>Address</th><th>Memory</th></tr>
<tr><td><p class="center">x</p></td><td>7ffd2063d858</td><td class="border"><p class="center"><span class="fragment fade-out" data-fragment-index="1">1</span><span class="fragment fade-in" data-fragment-index="1"><strong class="red">2</strong></span></p></td></tr>
<tr><td><p class="center">y</p></td><td>7ffd2063d860</td><td class="border"><p class="center">5</p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td><p class="center">x_pointer</p></td><td>...</td><td class="border" style="border-bottom:medium solid;"><p class="center">7ffd2063d858</p></td></tr>
</table>
</td><td></td><td>
<pre><code data-trim>*x_pointer = 2;
</code></pre>
<p>This means to dereference x_pointer</p>
</td></tr></table>
</script></section>
<section>
<h2>*x_pointer = 2</h2>
<img class="stretch" alt="Poitner code execution" src="images/01-cpp/pointers-2.png">
</section>
<section data-markdown><script type="text/template">
## x_pointer = &y
Source code: [pointers.cpp](code/01-cpp/pointers.cpp.html) ([src](code/01-cpp/pointers.cpp))
<table class="transparent"><tr><td>
<table class="transparent">
<tr><th>Variable</th><th>Address</th><th>Memory</th></tr>
<tr><td><p class="center">x</p></td><td>7ffd2063d858</td><td class="border"><p class="center">2</p></td></tr>
<tr><td><p class="center">y</p></td><td>7ffd2063d860</td><td class="border"><p class="center">5</p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td><p class="center">x_pointer</p></td><td>...</td><td class="border" style="border-bottom:medium solid;"><p class="center">7ffd2063d8<span class="fragment fade-out" data-fragment-index="1">58</span><span class="fragment fade-in" data-fragment-index="1"><strong class="red">60</strong></span></p></td></tr>
</table>
</td><td></td><td>
<pre><code data-trim>x_pointer = &y;
</code></pre>
<p>This means to get the address of y</p>
</td></tr></table>
</script></section>
<section>
<h2>x_pointer = &y</h2>
<img class="stretch" alt="Poitner code execution" src="images/01-cpp/pointers-3.png">
</section>
<section data-markdown><script type="text/template">
## *x_pointer = 3
Source code: [pointers.cpp](code/01-cpp/pointers.cpp.html) ([src](code/01-cpp/pointers.cpp))
<table class="transparent"><tr><td>
<table class="transparent">
<tr><th>Variable</th><th>Address</th><th>Memory</th></tr>
<tr><td><p class="center">x</p></td><td>7ffd2063d858</td><td class="border"><p class="center">2</p></td></tr>
<tr><td><p class="center">y</p></td><td>7ffd2063d860</td><td class="border"><p class="center"><span class="fragment fade-out" data-fragment-index="1">5</span><span class="fragment fade-in" data-fragment-index="1"><strong class="red">3</strong></span></p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td></td><td>...</td><td class="border"><p> </p></td></tr>
<tr><td><p class="center">x_pointer</p></td><td>...</td><td class="border" style="border-bottom:medium solid;"><p class="center">7ffd2063d860</p></td></tr>
</table>
</td><td></td><td>
<pre><code data-trim>*x_pointer = 3;
</code></pre>
<p>This means to dereference x_pointer</p>
</td></tr></table>
</script></section>
<section>
<h2>*x_pointer = 3</h2>
<img class="stretch" alt="Poitner code execution" src="images/01-cpp/pointers-4.png">
</section>
<section data-markdown><script type="text/template">
## Binky's Pointer Fun
<iframe width="720" height="540" src="http://www.youtube.com/embed/UvoHwFvAvQE?rel=0" frameborder="0" allowfullscreen></iframe>
If that doesn't work, try the [direct Youtube link](http://www.youtube.com/watch?v=UvoHwFvAvQE) (Firefox with Flash enabled doesn't work, in particular)
</script></section>
<section data-markdown><script type="text/template">
## What Types are These?
- `char * x;`
- `int **y;`
- `Rational *rNumber1;`
- `Square **blah;`
</script></section>
<section>
<h2>Pointer Pitfalls: Uninitialized Pointers</h2>
<ul><li>Cause runtime errors
<pre><code data-trim>int n = 30;
int * p;
*p = n; //ERROR!!!
</code></pre>
<ul><li>p does not have a valid memory address!</li>
<li>A common initializer value used by programmers is NULL
<pre><code data-trim>int *p=NULL; // better code, then add code to check
// for NULL value
</code></pre>
</li>
</ul></ul>
<script type="text/javascript">insertCanvas();</script>
</section>
<section>
<h2>swap()</h2>
<p>Source code: <a href="code/01-cpp/swap.cpp.html">swap.cpp</a> (<a href="code/01-cpp/swap.cpp">src</a>)</p>
<pre><code data-trim>void swap(int * x, int * y) {
int temp = *x;
*x = *y;
*y = temp;
}</code></pre>
<script type="text/javascript">insertCanvas();</script>
</section>
<section data-markdown><script type="text/template">
## Calling swap()
Source code: [swap.cpp](code/01-cpp/swap.cpp.html) ([src](code/01-cpp/swap.cpp))
```
int main() {
int a=0;
int b=3;
cout << "Before swap(): a: " << a << "b: "
<< b << endl;
swap(&b,&a);
cout << "After swap(): a: " << a << "b: "
<< b << endl;
return 0;
}
```
</script></section>
</section>
<section>
<section id="dynamic" data-markdown><script type="text/template">
# Dynamic Memory<br>Allocation
</script></section>