Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create DynamicAllocation #809

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions tutorials/learn-cpp.org/en/DynamicAllocation
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

# Dynamic Allocation in C++

## Tutorial
Dynamic memory allocation in C++ allows memory to be allocated at runtime using the `new` keyword. This is useful when the size of data is unknown until the program is running. Once dynamically allocated, memory must be manually deallocated using the `delete` keyword to avoid memory leaks.

### Key points:
- Use `new` to allocate memory.
- Use `delete` to free memory when it’s no longer needed.
- It’s typically allocated on the heap.

## Exercise
Write a program that dynamically allocates memory for an integer, assigns it a value, and then prints that value. Afterward, deallocate the memory using `delete`.

## Tutorial Code
```cpp
#include <iostream>

int main() {
int* ptr = nullptr; // Dynamically allocate memory for an int

// Assign a value to the allocated memory

// Print the value

// Deallocate memory

return 0;
}
```

## Expected Output
```
The value of the dynamically allocated integer is: 42
```

## Solution
```cpp
#include <iostream>

int main() {
int* ptr = new int; // Dynamically allocate memory for an int
*ptr = 42; // Assign a value to the allocated memory
std::cout << "The value of the dynamically allocated integer is: " << *ptr << std::endl;
delete ptr; // Deallocate memory
return 0;
}
```