From 595bfe2f4e78b8afe5a03990e9b2d47048e43f66 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 26 Jan 2024 13:42:40 -0500 Subject: [PATCH] adding another example for exercise --- lectures/06_memory/README.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/lectures/06_memory/README.md b/lectures/06_memory/README.md index 0ae779b..8aba054 100644 --- a/lectures/06_memory/README.md +++ b/lectures/06_memory/README.md @@ -105,7 +105,7 @@ other than the pointer variable. - Play this [animation](https://jidongxiao.github.io/CSCI1200-DataStructures/animations/dynamic_memory/example1/index.html) to see what exactly the above code snippet does. -## 6.2.1 Exercise +### 6.2.1 Exercise What’s the output of the following code? @@ -123,6 +123,38 @@ delete p; delete q; ``` +### 6.2.2 Exercise + +In the following program, which variable is stored in the stack? + +```cpp +#include + +void func1() { + int a = 42; + std::cout << "a: " << a << std::endl; +} + +void func2() { + int* b = new int(42); + std::cout << "b: " << *b << std::endl; + delete b; +} + +int c = 42; +static int d = 42; + +int main() { + func1(); + func2(); + + std::cout << "c: " << c << std::endl; + std::cout << "d: " << d << std::endl; + + return 0; +} +``` + ## 6.3 Dynamic Allocation of Arrays - How do we allocate an array on the stack? What is the code? What memory diagram is produced by the code? - Declaring the size of an array at compile time doesn’t offer much flexibility. Instead we can dynamically allocate an array based on data. Here’s an example: