e03-02.cpp
来自「游戏开发数据结构-Data.Structures.for.Game.Progra」· C++ 代码 · 共 57 行
CPP
57 行
// =======================================================
// 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 + =
减小字号Ctrl + -
显示快捷键?