You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/posts/cpp-learn.md
+67Lines changed: 67 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1629,6 +1629,73 @@ int main() {
1629
1629
}
1630
1630
```
1631
1631
1632
+
-**pointer-to-pointers**:
1633
+
- a pointer that holds the address of another pointer.
1634
+
- Using two asterisks to declare a pointer to pointer.
1635
+
- e.g. `int** ptrptr;`
1636
+
- Usages:
1637
+
- Dynamically allocate an array of pointers
1638
+
- e.g. `int** array { new int*[10] }; // allocate an array of 10 int pointers`
1639
+
- Two-dimensional dynamically allocated arrays
1640
+
- e.g. `int x { 7 }; // non-constant
1641
+
int (*array)[5] { new int[x][5] }; // rightmost dimension must be constexpr`
1642
+
1643
+
<br>
1644
+
1645
+
-**void-pointers**: Also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type
1646
+
- Dereferencing a void pointer is illegal. Instead, the void pointer must first be cast to another pointer type before the dereference can be performed.
1647
+
- We do not know what type of object it is pointing to, deleting a void pointer will result in undefined behavior.
1648
+
1649
+
<br>
1650
+
1651
+
-**function-pointers**:
1652
+
- e.g.
1653
+
```cpp
1654
+
// fcnPtr is a pointer to a function that takes no arguments and returns an integer
1655
+
int (*fcnPtr)();
1656
+
```
1657
+
1658
+
- Assigning a function to a function pointer: just like a normal pointer, and the type (parameters and return type) of the function pointer must match the type of the function.
fcnPtr1 = &hoo; // wrong -- fcnPtr1 has no parameters, but hoo() does
1671
+
int (*fcnPtr3)(int){ &hoo }; // okay
1672
+
```
1673
+
1674
+
- Calling a function using function pointer: There are two way to do this
1675
+
- Explicitly derefence
1676
+
- Implicitly derefence
1677
+
- e.g.
1678
+
```cpp
1679
+
intfoo(int x)
1680
+
{
1681
+
return x;
1682
+
}
1683
+
1684
+
int main()
1685
+
{
1686
+
int (*fcnPtr)(int){ &foo }; // Initialize fcnPtr with function foo
1687
+
(*fcnPtr)(5); // call function foo(5) through fcnPtr.
1688
+
1689
+
int (*fcnPtr2)(int){ &foo }; // Initialize fcnPtr with function foo
1690
+
fcnPtr2(5); // call function foo(5) through fcnPtr2.
1691
+
1692
+
return 0;
1693
+
}
1694
+
```
1695
+
- Passing functions as arguments to other functions: One of the most useful things to do with function pointers is pass a function as an argument to another function. Functions used as arguments to another function are sometimes called **callback functions**.
0 commit comments