实现一维动态数组
include
include<malloc.h>
using namespace std;
void output(int n)
{
int* arr = (int*)malloc(sizeof(int) * n);//在c++中,则是int * arr = new int[n];
if (arr == NULL)
return;
for (int i = n; i <= 2 * n - 1; i++)
{
arr[i-n] = i;
cout << arr[i-n] << " ";
}
free(arr);
}
int main()
{
int n;
cin >> n;
output(n);
}
实现二维动态数组
void output(int n)
{
int** arr;
arr = (int**)malloc(sizeof(int) * n);//在c++中,则是arr = new int [n];
if (arr == NULL)
return;
for (int i = 0; i < n; i++)
{
arr[i] = (int*)malloc(sizeof(int) * n);//在c++中,则是arr[i] = new int[n];
if (arr[i] == NULL)
return;
for (int j = 0; j < n; j++)
{
*(*(arr + i) + j) = i + j;//或者arr[i][j] = i + j;
cout << *(*(arr + i) + j) << " ";//或者cout << arr[i][j] << " "
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
output(n);
}