2016-03-16 23 views
-1

我正在尋找一種方法來訪問通過指針傳遞的多維數組。我在這裏跟着這個問題(Create a pointer to two-dimensional array)來創建我的數組和一個指向它的指針。我甚至可以將指針傳遞給函數,但是我不能使用指針來訪問數組值。訪問函數內部值的正確方法是什麼?訪問多維數組傳遞到函數

main.cpp中:

MyArrayGenerator theArrGen = MyArrayGenerator(); 
const int size = 9; 
int generatorArray[size][size][10]; 

theArrGen.generateArray(size, generatorArray[size][size+1]); 

在我的類中的方法:

void MyArrayGenerator::generateArray(int size,int* pointerToMultiDimArr) 
{ 
    int height = size + 1; 
    // this ptr points to the array address 
    int* ptr = pointerToMultiDimArr; 
    // not working: 
    ptr[1][1][1] = 123; 
} 

,這將引發的編譯器錯誤https://msdn.microsoft.com/de-de/library/fhexbxk9.aspx至極意味着指示器未聲明爲陣列。

我想我的方法參數需要改變,因爲它需要一個指針,並不知道它將是一個數組。我的問題是:方法參數應該如何顯示,以及在該方法之後如何訪問我的方法中的數組。後來我想用戶輸入的多維數組的大小和

const int size = 9; 

只是一個佔位符

+0

爲什麼你把它標記爲* C *? –

+0

抱歉,認爲這個問題在兩者之間可以互換。刪除了C標籤。 – TheCell

+0

帶類的語言是C++,而不是C,並且沒有多維數組。指針甚至不是一維數組。 – Olaf

回答

0

使用指針表示法訪問的元素!這裏是一個訪問和使用二維數組指針的例子,這個程序打印矩陣的轉置

#include<iostream> 
int **arr_input(int row, int col) 
{ 
    int **arr; 
    arr = new int*[row]; 
    for (int i = 0; i < row; i++)  //array size 
    { 
     *(arr + i) = new int[col]; 
    } 
    for (int i = 0; i < row; i++) 
    { 
     for (int j = 0; j < col; j++) 
     { 
      cin >> *(*(arr + i) + j); 
     } 
    } //input array 
    return arr; 
} 


void transpose(int**arr, int row, int col) 
{ 
    for (size_t i = 0; i < row; i++) 
    { 
     for (size_t j = 0; j < col; j++) 
     { 
      cout << *(*(arr + j) + i) << " ";  //pointer notation// 
     } 
     cout << endl; 
    } 
} 
void main(){ 
      int row ,col,**ptr1; 
     cout << "Enter size of Square Matrix: "; cin >> row; col = row; 
     cout << "\n\tEnter the elements of Matrix\n"; 
     ptr1 = arr_input(row, col); //calling array input function 
     cout << "\nAdress of pointer is " << ptr1<<endl; 
     transpose(ptr1, row, col); //calling transpose function 
     system("pause"); 
    } 
+0

問題在於接收功能對維度的容量不瞭解。如果沒有維度的能力,對「arr [1] [2] [1]」的評估就沒有意義。第二維可能有5個元素,它可能有512. –

+0

感謝實際試圖回答,而不僅僅是指責:)。這是否意味着如果我想要一個多維數組,我需要一個指向指針的指針,然後指向數組。我還需要一個for循環來創建多維數組(arr_input方法)?或者可以通過'int myArr [3] [3] [3];'創建數組。 – TheCell