Jump to content

How to Allocate Dynamic Memory (C++)

From freem
Revision as of 08:36, 21 March 2023 by Lukegao1 (talk | contribs) (创建页面,内容为“In C++, dynamic memory allocation allows you to allocate memory during runtime rather than at compile time. This is useful when you don't know the size of the memory required until runtime or when the size of the required memory changes during runtime. To allocate dynamic memory in C++, you can use the `new` keyword or the `malloc()` function. Here's how to use each of them: 1. Using `new` keyword: The `new` keyword is used to allocate memory for a single ob…”)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In C++, dynamic memory allocation allows you to allocate memory during runtime rather than at compile time. This is useful when you don't know the size of the memory required until runtime or when the size of the required memory changes during runtime.

To allocate dynamic memory in C++, you can use the `new` keyword or the `malloc()` function. Here's how to use each of them:

1. Using `new` keyword:

The `new` keyword is used to allocate memory for a single object. Here's an example:

```c++ int* p = new int; // Allocates memory for a single integer

  • p = 10; // Sets the value of the allocated memory to 10

```

In the above example, we are allocating memory for a single integer and assigning the value 10 to it. Note that we can use the dereference operator (`*`) to access the value stored in the allocated memory.

To deallocate the memory allocated using `new`, you can use the `delete` keyword as follows:

```c++ delete p; // Deallocates the memory allocated using new ```

2. Using `malloc()` function:

The `malloc()` function is used to allocate memory for multiple objects. Here's an example:

```c++ int n = 5; // Number of integers to allocate memory for int* p = (int*)malloc(n * sizeof(int)); // Allocates memory for n integers

for (int i = 0; i < n; i++) {

   *(p + i) = i + 1; // Sets the value of each integer to its index + 1

} ```

In the above example, we are allocating memory for n integers and assigning the value of each integer to its index + 1. Note that we can use pointer arithmetic to access the value stored in the allocated memory.

To deallocate the memory allocated using `malloc()`, you can use the `free()` function as follows:

```c++ free(p); // Deallocates the memory allocated using malloc ```

It's important to note that when using `malloc()`, you must cast the result to the appropriate type of pointer before assigning it to a pointer variable. Additionally, `malloc()` returns a `void*` pointer, which cannot be dereferenced. Therefore, you must use pointer arithmetic to access the value stored in the allocated memory.