From 9d03208b319c260aca7f811e26dd0daa024e22ae Mon Sep 17 00:00:00 2001 From: eggy Date: Thu, 27 Oct 2022 13:33:06 -0400 Subject: [PATCH] ece150: add pointers --- docs/ce1/ece150.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 7af8d39..6e88f08 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -169,3 +169,37 @@ The return value of the function overwrites whatever is at the bottom of the fun C-style strings are char arrays that end with a **null terminator** (`\0`). By default, char arrays are initialised with this character. If there is not a null terminator, attempting to access a string continues to go down the call stack until a zero byte is found. + +## Dynamic allocation + +Compared to static memory allocation, which is done by the compiler, dynamic memory is managed by the developer, and is stored between the call stack and data segment in the **heap**. + +## Pointers + +!!! definition + - A **pointer** is a variable that stores a memory address. + +The asterisk `*` indicates that the variable is a pointer address and can be **dereferenced**. `&` can convert an identifier to a pointer. + +```cpp +int array[10]; +int *p_array{array}; + +int num{2}; +int *p_num{&num}; +``` + +!!! warning + Only **addresses** should be passed when assigning pointer variables — this means that primitive types must be converted first to a reference with `&`. + +The default size of a pointer (the address size) can be found by taking the `sizeof` of any pointer. + +```cpp +sizeof(int*);` +``` + +The memory at the location of the pointer can be accessed by setting the pointer as the lvalue: + +```cpp +*var = 100; +```