1. 程式人生 > >C++快速入門---動態陣列(24)

C++快速入門---動態陣列(24)

C++快速入門---動態陣列(24)

 

編寫一個程式為一個整數型陣列分配記憶體,實現動態陣列。能夠在程式執行時讓使用者輸入一個值,自行定義陣列的長度。

 

新建一個動態陣列

例如:

int *x = new int[10];

可以像對待一個數組那樣使用指標變數x:

x[1] = 45;

x[2] = 8;

 

刪除一個動態陣列

delete []x;

 

#include <iostream>
#include <string>

int main()
{
	unsigned int count = 0;
	
	std::cout << "請輸入陣列的元素個數:\n";
	std::cin >> count;
	
	//在程式執行時,堆裡面申請記憶體 
	int *x = new int[count];//陣列名
	
	for(int i = 0; i < count; i++)
	{
		x[i] = i;
	}
	
	for(int i = 0; i < count; i++)
	{
		std::cout << "x[" << i << "]的值是:" << x[i] << "\n"; 
	}
	
	return 0;
}