动态申请一维数组
申请使用new,释放使用delete[]
可以通过数组名[下标]和*(数组名+下标)的方式访问数组
int main()
{
int number = 10;
int *array = new int[number];
//数组初始化
for (int i = 0; i < number; ++i)
{
array[i] = i;
}
for (int i = 0; i < number; ++i)
{
cout << *(array + i) << " ";
}
cout << endl;
//使用完以后记得释放哦
delete[] array;
return 0;
}
动态申请二维数组
二维数组的申请需要循环地申请二维数组的行指针。
int main()
{
int row = 10;
int column = 10;
//申请空间
int **matrix = new int*[row];
for (int i = 0; i < row; ++i)
{
matrix[i] = new int[column];
}
//矩阵初始化
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
matrix[i][j] = i * 10 + j;
}
}
//矩阵输出
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
if (i == 0) cout << ‘0‘;
cout << matrix[i][j] << ‘ ‘;
}
cout << ‘\n‘;
}
cout << endl;
//使用完以后记得释放哦
for (int i = 0; i < row; ++i)
{
delete[] matrix[i];
}
delete[] matrix;
return 0;
}
输出结果:
时间: 2024-12-28 16:22:40