Repository navigation
Expand file tree
/
Copy pathpointers.cpp
More file actions
68 lines (60 loc) · 2.71 KB
/
Copy pathpointers.cpp
File metadata and controls
68 lines (60 loc) · 2.71 KB
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
// Pointers: addresses, dereferencing, pointer arithmetic, pointers and arrays,
// pointer to pointer, const with pointers and dynamic memory (new / delete).
#include <iostream>
int main() {
int value = 42;
int* ptr = &value; // ptr holds the address of value
std::cout << "--- Basics ---\n";
std::cout << "value = " << value << '\n';
std::cout << "&value = " << &value << " (address in memory)\n";
std::cout << "ptr = " << ptr << " (the same address)\n";
std::cout << "*ptr = " << *ptr << " (dereference: the value at that address)\n";
*ptr = 100;
std::cout << "after *ptr = 100, value = " << value << "\n\n";
std::cout << "--- Pointer to pointer ---\n";
int** pptr = &ptr;
std::cout << "**pptr = " << **pptr << "\n\n";
std::cout << "--- Pointers and arrays ---\n";
int numbers[] = {10, 20, 30, 40, 50};
int* p = numbers; // an array name decays to a pointer to its first element
for (int i = 0; i < 5; ++i) {
std::cout << "*(p + " << i << ") = " << *(p + i) << " at " << (p + i) << '\n';
}
std::cout << "Each step moves sizeof(int) = " << sizeof(int) << " bytes\n";
int* last = &numbers[4];
std::cout << "last - p = " << (last - p) << " elements apart\n\n";
std::cout << "--- const and pointers ---\n";
int a = 1, b = 2;
const int* toConst = &a; // can't change the value through it, can point elsewhere
toConst = &b;
int* const constPtr = &a; // can change the value, can't point elsewhere
*constPtr = 10;
std::cout << "*toConst = " << *toConst << ", a = " << a << "\n\n";
std::cout << "--- Dynamic memory (heap) ---\n";
int n = 6;
int* squares = new int[n];
for (int i = 0; i < n; ++i) squares[i] = i * i;
std::cout << "Dynamic array: ";
for (int i = 0; i < n; ++i) std::cout << squares[i] << ' ';
std::cout << '\n';
delete[] squares; // every new[] needs a matching delete[]
squares = nullptr; // so it can't be used by mistake (dangling pointer)
// Jagged 2D array: each row has a different length
int rows = 6;
int** pascal = new int*[rows];
for (int i = 0; i < rows; ++i) {
pascal[i] = new int[i + 1];
pascal[i][0] = pascal[i][i] = 1;
for (int j = 1; j < i; ++j) pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
std::cout << "Pascal's triangle in a jagged array:\n";
for (int i = 0; i < rows; ++i) {
for (int j = 0; j <= i; ++j) std::cout << pascal[i][j] << ' ';
std::cout << '\n';
}
for (int i = 0; i < rows; ++i) delete[] pascal[i];
delete[] pascal;
int* nothing = nullptr;
if (nothing == nullptr) std::cout << "\nAlways check a pointer for nullptr before dereferencing it.\n";
return 0;
}