當前位置:學問谷 >

行政範例 >請示 >

動態內存空間的申請示範

動態內存空間的申請示範

利用C++的'特性,能夠自定義空間的類型大小和空間長度

動態內存空間的申請示範

下面這個程序是個數組動態配置的簡單示例

複製代碼 代碼如下:

#include

using namespace std;

int main()

{ int size = 0;

cout << "請輸入數組長度:"; //能夠自定義的動態申請空間長度

cin >> size;

int *arr_Point = new int[size];

cout << "指定元素值:" << endl;

for(int i = 0; i < size; i++)

{ cout << "arr[" << i << "] = ";

cin >> *(arr_Point+i);

}

cout << "顯示元素值:" << endl;

for(int i = 0; i < size; i++)

{ cout << "arr[" << i << "] = " << *(arr_Point+i)

<< endl;

}

[] arr_Point;

return 0;

}

執行結果:

複製代碼 代碼如下:

請輸入數組長度:5

指定元素值:

arr[0] = 1

arr[1] = 2

arr[2] = 3

arr[3] = 4

arr[4] = 5

顯示元素值:

arr[0] = 1

arr[1] = 2

arr[2] = 3

arr[3] = 4

arr[4] = 5

可以使用指針來仿真二維數組,只要清楚二維數組中的兩個維度的索引值之位移量就可以

複製代碼 代碼如下:

#include

using namespace std;

int main()

{ int m = 0;

int n = 0;

cout << "輸入二維數組維度:";

cin >> m >> n;

int *ptr = new int[m*n];

for(int i = 0; i < m; i++)

{ for(int j = 0; j < n; j++)

{ *(ptr + n*i + j) = i+j;

}

}

for(int i = 0; i < m; i++)

{ for(int j = 0; j < n; j++)

{ cout << *(ptr+n*i+j) << "t";

}

cout << endl;

}

[] ptr;

return 0;

}

標籤: 動態內存
  • 文章版權屬於文章作者所有,轉載請註明 https://xuewengu.com/flxz/qingshi/ved515.html