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:22] dwheele |
programming:cplusplus:start [2022/02/28 18:43] (current) dwheele [Reference] |
||
|---|---|---|---|
| Line 42: | Line 42: | ||
| // void* ptr = 0; // or void* ptr = nullptr; | // void* ptr = 0; // or void* ptr = nullptr; | ||
| int var = 8; | int var = 8; | ||
| - | // Where are you in memoary | + | // Where are you in memory |
| - | void* ptr = &var; | + | int* ptr = & |
| + | |||
| + | *ptr = 9; // int value pointed at by pointer " | ||
| | | ||
| Line 49: | 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; | ||
| + | | ||
| + | | ||
| + | } | ||
| + | |||
| + | </ | ||