1int myvar = 6;
2int pointer = &myvar; // adress of myvar
3int value = *pointer; // the value the pointer points to: 6
1#include <iostream>
2
3using namespace std;
4
5int main () {
6 int var = 20; // actual variable declaration.
7 int *ip; // pointer variable
8
9 ip = &var; // store address of var in pointer variable
10
11 cout << "Value of var variable: ";
12 cout << var << endl; //Prints "20"
13
14 // print the address stored in ip pointer variable
15 cout << "Address stored in ip variable: ";
16 cout << ip << endl; //Prints "b7f8yufs78fds"
17
18 // access the value at the address available in pointer
19 cout << "Value of *ip variable: ";
20 cout << *ip << endl; //Prints "20"
21
22 return 0;
23}
1Every object in C++ has access to its own address through an important pointer called this pointer.
2 The this pointer is an implicit parameter to all member functions.
3Therefore, inside a member function,
4 this may be used to refer to the invoking object.
5
6Friend functions do not have a this pointer,
7 because friends are not members of a class.
8Only member functions have a this pointer.
1void simple_pointer_examples() {
2 int a; // a can contain an integer
3 int* x; // x can contain the memory address of an integer.
4 char* y; // y can contain the memory address of a char.
5 Foo* z; // z can contain the memory address of a Foo object.
6
7 a = 10;
8 x = &a; // '&a' extracts address of a
9
10 std::cout << x << std::endl; // memory address of a => 0x7ffe9e25bffc
11 std::cout << *x << std::endl; // value of a => 10
12}
1void one() { cout << "One\n"; }
2void two() { cout << "Two\n"; }
3
4
5int main()
6{
7 void (*fptr)(); //Declare a function pointer to voids with no params
8
9 fptr = &one; //fptr -> one
10 *fptr(); //=> one()
11
12 fptr = &two; //fptr -> two
13 *fptr(); //=> two()
14
15 return 0;
16}
17
1#include <iostream>
2
3using namespace std;
4// isualize this on http://pythontutor.com/cpp.html#mode=edit
5int main()
6{
7 double* account_pointer = new double;
8 *account_pointer = 1000;
9 cout << "Allocated one new variable containing " << *account_pointer
10 << endl;
11 cout << endl;
12
13 int n = 10;
14 double* account_array = new double[n];
15 for (int i = 0; i < n; i++)
16 {
17 account_array[i] = 1000 * i;
18 }
19 cout << "Allocated an array of size " << n << endl;
20 for (int i = 0; i < n; i++)
21 {
22 cout << i << ": " << account_array[i] << endl;
23 }
24 cout << endl;
25
26 // Doubling the array capacity
27 double* bigger_array = new double[2 * n];
28 for (int i = 0; i < n; i++)
29 {
30 bigger_array[i] = account_array[i];
31 }
32 delete[] account_array; // Deleting smaller array
33 account_array = bigger_array;
34 n = 2 * n;
35
36 cout << "Now there is room for an additional element:" << endl;
37 account_array[10] = 10000;
38 cout << 10 << ": " << account_array[10] << endl;
39
40 delete account_pointer;
41 delete[] account_array; // Deleting larger array
42
43 return 0;
44}