#include "stdio.h"
#include "vector"
int main()
{
printf("Hello main \n");
int row = 3;
int col = 4;
/*********************************************************/
/********************* static ****************************/
int array21[row][col]; //static
int num_all = sizeof(array21)/sizeof(int);
int num_col = sizeof(array21[0])/sizeof(int);
int num_row = num_all/num_col;
printf("num_all=%d num_row=%d num_col=%d\n", num_all, num_row, num_col);
int array22[row][col] = {1, 2, 3, 4};
printf("\nAccess array22 elements (element without initialization is zero):\n");
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
printf("%d ", array22[i][j]);
}
printf("\n");
}
int array23[row][col] = { {1,2}, {3,4}, {5,6} };
printf("\nAccess array23 elements (element without initialization is random):\n");
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
printf("%d ", array23[i][j]);
}
printf("\n");
}
/**********************************************************/
/*********************** dynamic **************************/
int (*array24)[3] = new int[row][3]; //3 must be a constant value
delete array24;
/*************************************************/
int **array25 = new int *[row];
for(int i=0; i<row; i++)
{
array25[i] = new int[col];
}
// access array elements
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
array25[i][j] = i * col + j;
}
}
// delete low-level dynamic array
for(int i=0; i<row; i++)
{
delete array25[i];
}
// then delete high-level dynamic array
delete array25;
/***********************************************************************/
/********************** dynamic using vector ***************************/
typedef std::vector<int> IntVector;
typedef std::vector<IntVector> IntVector2D;
IntVector2D *array26 = new IntVector2D;
// set array size dynamically
array26->resize(row);
for(int i=0; i<row; i++)
{
(*array26)[i].resize(col);
}
// access array elements
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
(*array26)[i][j] = i * col + j;
}
}
delete array26;
/*************************************************/
printf("\nGoodbye main \n");
}
运行结果:
Hello main
num_all=12 num_row=3 num_col=4
Access array22 elements (element without initialization is zero):
1 2 3 4
0 0 0 0
0 0 0 0
Access array23 elements (element without initialization is random):
1 2 64 0
3 4 4201077 0
5 6 -392893904 32762
Goodbye main