📄 e03-02.cpp
字号:
// =======================================================
// Chapter 3, Example 2
// Demonstrating Dynamic Arrays.
// =======================================================
#include <malloc.h>
// -------------------------------------------------------
// Name: ArrayFunction
// Description: sets array[0] to 10.
// Arguments: - p_array: the array
// -------------------------------------------------------
void ArrayFunction( int p_array[] )
{
p_array[0] = 10;
}
void main()
{
// declare 3 array pointers, and set them to 0.
int* array1 = 0;
int* array2 = 0;
int* array3 = 0;
// allocate an array with 10 cells using malloc.
array1 = (int*)malloc( 10 * sizeof(int) );
// allocate an array with 10 cells using calloc.
array2 = (int*)calloc( 10, sizeof(int) );
// allocate an array with 10 cells using new.
array3 = new int[10];
// resize array1 and array2 using realloc.
// note that the end of array2 will not have '0's in it.
array1 = (int*)realloc( array1, 20 * sizeof(int) );
array2 = (int*)realloc( array2, 20 * sizeof(int) );
// resize array3 using the resize algorithm.
int* temp = 0;
int index;
temp = new int[20];
for( index = 0; index < 10; index++ )
temp[index] = array3[index];
delete[] array3;
array3 = temp;
temp = 0;
// free the first two arrays using free.
free( array1 );
free( array2 );
// free the third array using delete[]
delete[] array3;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -