Dynamically Allocating Integer Arrays in C
When working with data in programming, it is often necessary to store collections of elements. In C , Arrays provide a convenient way to store such data, but sometimes, we cannot predict the required data size, which complicates the creation of static arrays of specific sizes. In this case, you can use dynamic arrays, which allow allocation and resizing as needed at execution time.
Use the new keyword to create a dynamic array
In C, you can use the new keyword to dynamically allocate memory. To create a dynamic integer array, perform the following steps:
Example кода
Here is a sample code that creates a dynamic array of integers and processes its elements:
int main() { int size; std::cin >> size; int *array = new int[size]; // 訪問和更新元素 for (int i = 0; i < size; i++) { array[i] = i + 1; } // 打印元素 for (int i = 0; i < size; i++) { std::cout << array[i] << " "; } // 釋放分配的內存 delete[] array; return 0; }
Note:
Dynamic memory allocation, although useful, may also lead to memory leaks if the delete or delete[] operators are not called on memory that is no longer in use. Therefore, it is important to always ensure that allocated memory is freed when finished.
The above is the detailed content of How to Dynamically Allocate Integer Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!