C/C++创建动态数组

创建动态数组的功能常用于函数中,malloc或者vector函数接收到参数后再创建数组 

//C:使用用malloc函数创建动态数组
//一维 b[x]
 	 b = (int *)malloc(sizeof(int)* x);
//二维 p[a][b]
 	 p = (int**)malloc(sizeof(int*)*a);
	 for (i = 0; i<a i++)
		 p[i] = (int*)malloc(sizeof(int)*b);
//C++:用vector函数创建长度为length的动态数组
#include <iostream>  
#include <vector>  
using namespace std;  
  
int main()  
{  
    int length, i;  
	cout <<"Enter the length of an array: " <<endl;  
 	cin >>length;  
  	vector<int> a(length);  
	for(i=0; i<length; i++)  
      a[i] = i;  

  	cout <<"输入的数组为:" <<endl;  
 	 for(i=0; i<length; i++)  
      cout <<"a[" <<i <<"] = " <<a[i] <<endl;  

 	system("pause");  
  	return 0;  
}
	
点赞