adding another example for exercise

This commit is contained in:
Jidong Xiao
2024-01-26 13:42:40 -05:00
parent 93fa178d97
commit 595bfe2f4e

View File

@@ -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. - 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
Whats the output of the following code? Whats the output of the following code?
@@ -123,6 +123,38 @@ delete p;
delete q; delete q;
``` ```
### 6.2.2 Exercise
In the following program, which variable is stored in the stack?
```cpp
#include <iostream>
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 ## 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? - 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 doesnt offer much flexibility. Instead we can dynamically allocate an array based on data. Heres an example: - Declaring the size of an array at compile time doesnt offer much flexibility. Instead we can dynamically allocate an array based on data. Heres an example: