In C, dynamic arrays can allocate and free memory at runtime. The steps to define a dynamic array include: (1) allocate memory using the new operator; (2) initialize the array elements; (3) use the dynamic array; (4) use the delete[] operator to release the memory.
How to define a dynamic array in C
In C, a dynamic array is a type that can be used## The #new and
delete operators allocate and free memory for array types at runtime. The following are the steps to define a dynamic array:
1. Allocate memory using the new operator
new operator Used to dynamically allocate memory of a specified type and size. For an integer dynamic array, the syntax is as follows:
<code class="cpp">int *array = new int[size];</code>
is a pointer variable pointing to the dynamic array.
is the size of the array.
2. Initialize array elements
The memory allocated by the dynamic array is not initialized. You can use the array access operator ([]) to initialize elements as follows:
<code class="cpp">for (int i = 0; i < size; i++) { array[i] = i; }</code>
3. Using dynamic arrays
Dynamic arrays Can be used like a normal array. You can access elements, modify elements, and even get the size of an array. You can use thesizeof operator to get the size of the array, as shown below:
<code class="cpp">int array_size = sizeof(array) / sizeof(array[0]);</code>
4. Release memory
When the dynamic array is no longer needed , you can use thedelete[] operator to free the allocated memory. This will free the memory pointed to by the array elements and pointer variables. The syntax is as follows:
<code class="cpp">delete[] array;</code>
Example
The following is an example of defining and using a dynamic array:<code class="cpp">#include <iostream> using namespace std; int main() { int size = 5; int *array = new int[size]; // 初始化数组元素 for (int i = 0; i < size; i++) { array[i] = i * i; } // 打印数组元素 for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; // 释放内存 delete[] array; return 0; }</code>
<code>0 1 4 9 16</code>
The above is the detailed content of How to define dynamic array in c++. For more information, please follow other related articles on the PHP Chinese website!