2017-02-10 144 views
1

所以我有問題使這個測試程序工作。所以我的目標是在主函數中創建並初始化3D數組,然後創建一個指向該數組的指針。之後,我試圖將指針傳遞給一個函數,然後打印出數組中的元素,以便我可以看到它的工作原理。當試圖傳遞指針數組tho時,我的問題就出現了。你們中的任何一個人看到我們會出錯嗎?傳遞3D指針數組到函數

#include <stdio.h> 

//declare test function 
void test (int*); 

int main(){ 

    //declare array and pointer 
    int array[2][3][2]; 
    int (*p)[2][3][2] = &array; 

    int i,j,k; 

    //initialize array 
    for(i = 0; i < 2; i++){ 
     for(j = 0; j < 3; j++){ 
      for(k = 0; k < 2; k++){ 
       array[i][j][k] = 0; 
      }  
     } 
    } 

    //print array 
    for(i = 0; i < 2; i++){ 
     for(j = 0; j < 3; j++){ 
      for(k = 0; k < 2; k++){ 
       printf("%d\n", array[i][j][k]); 
      }  
     } 
    } 
    printf("----------------------------\n\n"); 
    //pass pointer array into test function 
    test(p);  
} 


void test(int (*array2)[2][3][2]){ 
    int i, j, k; 
    //run thru each element in the pointer array and print 
    for(i = 0; i < 2; i++){ 
     for(j = 0; j < 3; j++){ 
      for(k = 0; k < 2; k++){ 
       printf("%d\n", array2[i][j][k]); 
      }  
     } 
    }   
} 
+0

'空隙測試(INT數組2 [2] [3] [2])'和通過調用'試驗(陣列)轉儲'p'東西;'和變化函數原型來匹配它的實現。 –

+0

我可以做到這一點,但它不會發送數組的指針。即時通訊試圖找出如何做到這一點,以便我可以稍後修改函數中的數組通過指針 – cooldude22

+0

數組通過衰減到指針。函數定義告訴如何使用它。 –

回答

0

如果您選擇使用:

int array[2][3][2]; 
int (*p)[2][3][2] = &array; 

於是,線路

  printf("%d\n", array2[i][j][k]); 

test需求是:

  printf("%d\n", (*array2)[i][j][k]); 

你也可以使用:

int array[2][3][2]; 
int (*p)[3][2] = array; 

然後,你需要的功能更改爲

void test(int (*array2)[3][2]){ 

void test(int array2[][3][2]){ 

,這將允許您使用:

  printf("%d\n", array2[i][j][k]); 
0

的數組傳遞衰減到指針,函數定義說明如何使用它。該函數不需要知道頂部數組維就能正確索引。

#include <stdio.h> 

void test(int array2[][3][2]); 

void test(int array2[][3][2]) 
{ 
    printf("In function %d\n", array2[1][1][1]); 
    array2[1][1][1] = 42; 
} 

int main(void) 
{ 
    int array[2][3][2] = {0}; 
    array[1][1][1] = 99; 
    test(array); 
    printf("In main %d\n", array[1][1][1]); 
    return 0; 
} 

程序輸出

In function 99 
In main 42