forked from eodus/cpp2014
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pointers_references.c++
90 lines (69 loc) · 1.48 KB
/
pointers_references.c++
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
#include <cstdio>
#include <new>
// typedef demo
// typedef int *pint;
// OR (moern way)
using pint = *int;
// typedef pint apint[];
// OR
// typedef int *apint[];
// OR (modern way)
using apint = *int[];
int main() {
// const and cast
{
const int *cpi = new int[10];
int *pi = (int*)cpi;
//cpi[0] = 10; //Error;
pi[0] = 10;
printf("%d\n", cpi[0]);
delete[] cpi;
}
// "Jagged" array
{
apint a = {new int[10], new int[11]};
a[0][0]; // till
a[0][9];
a[1][0]; // till
a[1][10];
// Kill'em all
// for (int i = 0; i < 2; ++i)
// delete[] a[i];
// OR (modern way)
// Kill'em all
for (auto p : a) delete[] a;
}
// Null pointer
{
int *p1 = nullptr; // modern way
int *p2 = 0; // oldschool way
int *p3 = NULL; // decorated oldschool way (NULL defined just like #define NULL 0)
if (!p1) {
// "If p1 is not correct..."
printf("p1 is not correct\n");
}
// Also one can use (p1 == nullptr)
}
// Reference pointer
{
int i = 10, j = 12;
int &li = i;
const int &lj = j;
++li;
// --lj; // Error, attemption to change constant
printf("%d %d %d %d", i, j, li, lj);
}
// Anti-example (UB) with pointers
{
int *pi;
{
int i = 42;
pi = &i;
}
int &li = *pi; // Refer to what? UB!
++li;
printf("%d\n", li); // UB. Maybe 43, but may be not...
// printf("%d\n", i); // Just error, "i" not in scope
}
return 0;
}