-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointers.cpp
More file actions
73 lines (55 loc) · 1.35 KB
/
pointers.cpp
File metadata and controls
73 lines (55 loc) · 1.35 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
69
70
71
72
73
#include <iostream>
using namespace std;
void swap(int *p, int *q);
void swap(int &p, int &q);
int main()
{
int var1;
char var2[10];
cout << "Address of var1: " << &var1 << endl;
cout << "Address of var2: " << &var2 << endl;
// What is a pointer ?
// A pointer is a variable that stores the address
// of some other variable;
int *i_pointer;
double *d_pointer;
float *f_pointer;
char *c_pointer;
int a = 20;
int *mPointer;
mPointer = &a;
cout << "\n\n";
// cout << "Adress of a: " << mPointer << endl;
// cout << "Value of a: " << *mPointer << endl;
// a = 100;
int b = 200;
cout << "\nBefore swapping: "
<< "A: " << a << " B: " << b;
// swap(&a, &b);
swap(a, b);
cout << "\nAfter swapping: "
<< "A: " << a << " B: " << b;
return 1;
}
// call by pointer
void swap(int *pointer1, int *pointer2)
{
int temp;
temp = *pointer1;
*pointer1 = *pointer2;
*pointer2 = temp;
return;
}
// call by reference :: wont create a copy
// ¶m1 -> here '&' tells the compiler that reference is shared.
void swap(int &address1, int &address2)
{
// here address1 and address 2
// are not copies of a and b.
// They are 'actually' a and b;
int temp;
temp = address1;
address1 = address2;
address2 = temp;
return;
}