diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 3c2a4ce..fd3e70b 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -18,7 +18,7 @@ Binary numbers are prefixed with `0b`. To convert from **binary to decimal**, each digit should be treated as a power of two much like in the base 10 system. !!! example - $$ + $$0 \text{0b1011}=1\times2^3 + 0\times2^2+1\times2^1+1\times2^0=11 $$ @@ -201,6 +201,39 @@ If deleting arrays, `delete[]` should be used instead. !!! warning Statically allocated memory **cannot be deallocated** manually as it is done so by the compiler, so differentiating the two is generally a good idea. +### Vectors at home + +Dynamic allocation can be used to mimick an `std::vector` by creating a new array whenever an element would be full and doubling its size, copying all elements over. + +!!! example + Sample implementation: + + ```cpp + std::size_t capacity{10}; + double *data{new double[capacity]}; + std::size_t els{0}; + + while (true) { + double x{}; + std::cin >> x; + + ++els; + if (els == capacity) { + std::size_t old_capacity{capacity}; + double *old_data{data}; + capacity *= 2; + data = new double[capacity]; + + for (int i{}; i < old_capacity; ++i) { + data[i] = old_data[i]; + } + + delete[] old_data; + old_data = nullptr; + } + } + ``` + ### Wild pointers A wild pointer is any uninitialised pointer. Its behaviour is undefined. Accessing unallocated memory results in a **segmentation fault**, causing the OS to terminate the program. @@ -266,3 +299,44 @@ The memory at the location of the pointer can be accessed by setting the pointer ```cpp *var = 100; ``` + +The `const` modifier only makes constant the value immediately after `const`, meaning that the expression after it cannot be used as an lvalue. + +!!! example + ```cpp + int* const p_x{&x}; + + p_x = &y; // not allowed + *p_x = y; // allowed + ``` + + ```cpp + int const *p_x{&x}; + + p_x = &y; // allowed + *p_x = y; // not allowed + ``` + + ```cpp + int const * const p_x{&x}; + + p_x = &y; // not allowed + *p_x = y; // not allowed + ``` + +Pointers to `const` values must also be `const`. + +!!! example + BAD: + ```cpp + const int x = 2; + int *p_x{&x}; + ``` + + GOOD: + ```cpp + const int x = 2; + int const *p_x{&x}; + ``` + +