我試着調試下面的代碼,並且出現「訪問衝突」錯誤。我不明白爲什麼第二個循環在訪問第二行元素時失敗,而第一個循環能夠訪問所有元素。2D陣列訪問衝突
我搞砸了*
,&
和[]
,但無法弄清楚。
謝謝。
#include <iostream>
void a(const int* data, unsigned int nElements, unsigned int nColumns) {
for (unsigned int i = 0; i < nElements; ++i)
std::cout << data[i];
for (unsigned int i = 0; i < nElements/nColumns; ++i)
for (unsigned int j = 0; j < nColumns; ++j)
std::cout << (&data)[i][j];
}
int main() {
int arr[2][5] = {
{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 }
};
a(*arr, 2 * 5, 5);
return 0;
}
你能解釋一下你想要做的更多嗎?有點不清楚。 – Ben
真正的問題在這裏:(&data)[i]。由於數據是參數中的單個元素,因此&data是指向單個元素的指針。這意味着i> 0是一個問題。多維數組實際上是一塊內存,當你在多維數組上進行[i] [j]操作時,編譯器將其與[i] [j]中的指針數組區別開來。多維數組上的[i] [j]與[i * numcolumns + j]相同。 – thang