COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
null_pointer.cpp
Go to the documentation of this file.
1#include <iostream>
2using namespace std;
3
4
5int main()
6{
7 int x = 0;
8 int * dangling_ptr;
9
10
11 cout << *dangling_ptr << endl; // this is unpredictable & dangerous!
12
13
14 int * ptr = nullptr; // initialize a ptr to 0
15
16 // cout << *ptr << endl; // this will crash the program!
17
18 // to be safe, check if the pointer is null
19 // or not before using it
20 if (ptr != nullptr)
21 cout << "1: " << *ptr << endl;
22
23
24 ptr = &x;
25
26 if (ptr != nullptr)
27 cout << "2: " << *ptr << endl;
28
29 return 0;
30}
int main()