int myArray[] = {1,2,3};
int *myPointer = myArray;
// We can change the value of the array's indexes.
// This line change the 2th index of myArray to 5.
*(myArray + 1) = 5;
for(int i = 0; i <= 2; i++) {
cout << i << "\n";
int a = 9;
int *p = &a;
int **pp = &p;
// Both has same data.
cout << *p << "\n";
cout << **pp << "\n";
// Basically the releationship is: **pp -> *p -> a=9
// You can also have 3 leveldeep pointer: ***p, which point to pointer of pointer.
int a[] = {1,2};
int b[] = {3,4,5};
// We have an array of pointers which the first index point to `a` array and the seconde index point to `b` array.
int *p[] = {a,b};
cout << *(p(1)+2); // 5
int a[2][3] = {1,2,3,4,5,6};
// Define a Pointer. It's size must be equal to array's column size.
int (*p)[3]; // It must point to all dimensions except the first one.
int *p[] = {a,b};
cout << *(*p + 1); // 2, points to the first row.
cout << *(p(1) + 2); // 5, points to the second row.
// If we have a function like:
int fn(int num) {
return num * num;
}
// Then we can also define a pointer like:
int (*p)(int);
// It means we have an pointer which accept and `int` parameter and returns `int` value that it can be used
// just like functions.
// Asign the funciton definition to pointer:
p = fn;
int k = p(554);
// When we call the pointer just like the function, it's action like function itself.
// If we have theese function prototypes:
int sum(int, int);
int prod(int, int);
// Then we can have arrays of pointers to functions.
// pass prototypes for array:
int (*p[2])(int, int) = {sum, prod};
int val = (*p[0])(2,3);
// If we have theese function prototypes:
int sum(int, int);
int prod(int, int);
int pointerFun(int (*p)(int, int), int, int);
// We can pass other functions as pointer to `pointerFun()`.
pointerFun(sum, 2,3);
pointerFun(prod, 2,3);
// Prototype:
void f(int *);
int a = 2;
f(&a);
// Prototype implementation:
void f(int *a) {
*a = *a+5; // We change the value by reference
}
You can use void
keyword for pointers declarations to act as ans genenric like variavle:
int a = 2;
float b = 2.5;
void *p;
*p = &a;
cout << *(int *)p;
*p = &b;
cout << *(int *)p;
// Error! -> cout << *p;
The new
keyword assign space to variables in Heap and not the program segment which not freed after end of the program. Make sure to run delete
after usage.
int *a = new int;
a = 2;
// End of the day:
delete a;
// You can specifie the value of the pointer in declaraition:
int *b = new int(3); // Menas b is 3.
int *c = new int[2]; // Allocate an array with 2 index.
delete []c;