- 相關(guān)推薦
動(dòng)態(tài)內(nèi)存空間的申請(qǐng)示范
利用C++的特性,能夠自定義空間的類型大小和空間長(zhǎng)度
下面這個(gè)程序是個(gè)數(shù)組動(dòng)態(tài)配置的簡(jiǎn)單示例
復(fù)制代碼 代碼如下:
#include
using namespace std;
int main()
{ int size = 0;
cout << "請(qǐng)輸入數(shù)組長(zhǎng)度:"; //能夠自定義的動(dòng)態(tài)申請(qǐng)空間長(zhǎng)度
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;
}
執(zhí)行結(jié)果:
復(fù)制代碼 代碼如下:
請(qǐng)輸入數(shù)組長(zhǎng)度: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
可以使用指針來(lái)仿真二維數(shù)組,只要清楚二維數(shù)組中的兩個(gè)維度的索引值之位移量就可以
復(fù)制代碼 代碼如下:
#include
using namespace std;
int main()
{ int m = 0;
int n = 0;
cout << "輸入二維數(shù)組維度:";
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;
}