This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
programming:cplusplus:start [2022/02/28 18:27] dwheele [Pointers] |
programming:cplusplus:start [2022/02/28 18:43] (current) dwheele [Reference] |
||
|---|---|---|---|
| Line 51: | Line 51: | ||
| </ | </ | ||
| + | <code c++> | ||
| + | int main() | ||
| + | { | ||
| + | char* buffer = new char[8];// This uses heap | ||
| + | | ||
| + | |||
| + | | ||
| + | |||
| + | | ||
| + | |||
| + | | ||
| + | } | ||
| + | </ | ||
| ===== Reference ===== | ===== Reference ===== | ||
| + | Pointers and references are about the same thing. How we write them is different. References are syntax sugar on top of a pointer. | ||
| + | |||
| + | References reference an existing variable. | ||
| + | |||
| + | <code c++> | ||
| + | int main() | ||
| + | { | ||
| + | int a =5; | ||
| + | | ||
| + | // We have created an alias. It is not really a variable. | ||
| + | // We can use ref as though it is " | ||
| + | |||
| + | ref = 2; | ||
| + | | ||
| + | } | ||
| + | // Works, but this is clumsy | ||
| + | |||
| + | void Increment (int* value) | ||
| + | { | ||
| + | | ||
| + | } | ||
| + | int main() | ||
| + | { | ||
| + | // We want to pass the memory address. | ||
| + | int a = 5; | ||
| + | | ||
| + | | ||
| + | } | ||
| + | |||
| + | </ | ||
| + | <code c++> | ||
| + | // Use a reference instead of a pointer | ||
| + | |||
| + | void Increment(int& | ||
| + | { | ||
| + | | ||
| + | } | ||
| + | int main() | ||
| + | { | ||
| + | int a = 5; | ||
| + | | ||
| + | | ||
| + | } | ||
| + | |||
| + | </ | ||