目前VS2013不支持動態數組,也就是int a[n], n必須是常量。創建動態數組可以使用 new 的方法。比如創建一個二維動態數組:
int n;
cin>>n;
int **matrix=new int*[n];//matrix是一個存放指向int類型指針的數組,它有n個元素。
for(int k=0;k<n;k++)
{
matrix[k]=new int[n];//視matrix爲一維數組,該語句爲matrix的每個元素賦值,每個元素存的是一段內存(用來存放n個int類型的值)的段首地址。
}
在測試這段程序時,輸入n爲3,那麼這個二維數組應該包含9個元素,matrix[i][j]中0<=i<=2, 0<=j<2,現在令matrix[0][18]=100,竟然沒有報錯。
經調試發現,matrix[0]和matrix[1]這兩個元素,所存儲地址之差並不是n*sizeof(int),而是遠遠大於這個數。具體測試代碼如下:
#include <iostream>
using namespace std;
int main( )
{
int n = 4;
int **matrix = new int*[n];
for (int k = 0; k < n; k++)
{
matrix[k] = new int[n];
}
matrix[0][0] = 0;
matrix[0][14] = 99;
matrix[0][16] = 100;
matrix[1][0] = 3;
cout << "The address of matrix[0][14] is : " << &matrix[0][14] << endl;
cout << "The address of matrix[0][16] is : " << &matrix[0][16] << endl;
cout << "The address of matrix[1][0] is : " << &matrix[1][0] << endl;
cout << "matrix[0][14] : " << matrix[0][14] << endl;
cout << "matrix[0][16] : " << matrix[0][18] << endl;
cout << "matrix[1][0] : " << matrix[1][0]<<endl;
return 0;
}
從以上運行結果可以看出matrix[0][16]和 matrix[1][0]的地址相同,既然是對同一地址進行存儲和讀取,則必然會出現錯誤(matrix[0][16]無法顯示100)。
而matrix[0][14]=99,雖然能夠正確顯示,但是它已經超出了new 分配的內存空間。雖然無法知道爲數組分配內存時,爲何分配的空間超出代碼要求的範圍,但是在使用動態數組的時候,一定不要超出數組界限,否則會帶來很多不必要的麻煩。
以上爲個人看法,有不同意見歡迎指正,謝謝。