Home >Backend Development >C++ >How to Create and Manage Dynamic Arrays in C Using the `new` Keyword?
Creating dynamic arrays allows you to allocate memory on the heap during runtime, providing flexibility in data storage. In C , the 'new' keyword is utilized to achieve this.
To create a dynamic array of integers using 'new,' follow these steps:
int main() { int size; std::cin >> size; int *array = new int[size];
The above code snippet defines an integer pointer named 'array' and allocates memory dynamically to store 'size' number of integers.
It's imperative to remember that dynamic memory allocation requires proper management to avoid memory leaks. Once the dynamic array is no longer required, it must be deleted using the 'delete[]' operator:
delete[] array;
This action deallocates the memory associated with the dynamic array, freeing it up for other purposes.
Consider the following example:
int main() { int size; std::cin >> size; int *array = new int[size]; // ... Code to manipulate the dynamic array ... // Memory cleanup delete[] array; return 0; }
In this example, we take user input for the desired size of the array, allocate memory accordingly, perform operations on the dynamic array, and finally release the allocated memory.
The above is the detailed content of How to Create and Manage Dynamic Arrays in C Using the `new` Keyword?. For more information, please follow other related articles on the PHP Chinese website!