动态分配内存可以使的程序在内存中更加灵活地使用
动态分配数组使用new函数
1 #include <iostream> 2 constexpr auto N = 5; 3 using namespace std; 4 void insert_sort(int a[], int n) //插入排序算法,对输入的数进行排序 5 { 6 int i, j, temp; 7 for (i = 0; i < n - 1; i++) 8 { 9 for (j = 0; j < n - i - 1; j++) 10 { 11 if (a[j] > a[j + 1]) 12 { 13 temp = a[j]; 14 a[j] = a[j + 1]; 15 a[j + 1] = temp; 16 } 17 } 18 } 19 } 20 int main() 21 { 22 int* pArray;//设置指针 23 int i; 24 pArray = new int[N]; //动态分配数组 25 //向数组中输入5个整数 26 for (i = 0; i < N; i++)//循环输入数值,使数值的数量不能小于5 27 cin >> pArray[i]; 28 insert_sort(pArray, N);//调用排序算法 29 for (i = 0; i < N; i++)//循环输入数值,使数值的数量不能小于5 30 cout << pArray[i] << " "; 31 system("pause"); 32 return 0; 33 }

浙公网安备 33010602011771号