2014-11-03 62 views
0

我在理解如何分配到Test陣列時遇到問題,如下所示:
int (*&Test)[10] = Parray;Test是對指向十個整數的指針的引用。

我得到的錯誤如下:如何分配數組int(*&Test)[10]?

error: incompatible types in assignment of 'int*' to 'int [10]'|.

我已經做了我的研究沒有完全理解這一點。我正在閱讀C++ Primer第5版。

int main() { 
    int arr[10]; 
    int n = 5; 
    int *ptr1 = &n; 
    int arr2[10]; 
    int *ptrs[10]; // ptrs is an array of ten pointers 

    // Parray points to an array of ten ints 
    int (*Parray)[10] = &arr; 
    // arrRef refers to an array of ten ints 
    int (&arrRef)[10] = arr2; 

    // Test is a reference to a pointer to an array of ten ints. 
    int (*&Test)[10] = Parray; 

    // How can I assign to Test[0..1..2..etc]? 
    // This is what I am trying to do: 
    Test[0] = ptr1; // Error here 

    return 0; 
} 

我該如何分配到Test[0]等?

+5

否測試是指向的10個整數的數組的指針的引用。 – texasbruce 2014-11-03 05:01:13

+0

^它與'arr'類型相同。如果你想要一個指針數組,你需要使用你的「師生比」變量某處 – Aralox 2014-11-03 05:10:12

+0

'ptr1'是未初始化的指針,它並不清楚你希望與'ptr1'和'ptrs'這裏 – 2014-11-03 05:14:11

回答

1

它應該是:

(*Test)[0] = 3; 
(*Test)[1] = 5; 

等。另外,你可以寫Test[0][0] = 3; Test[0][1] = 5;但是我認爲這是不太清楚。

Test是相同類型Parray參考。取消引用會得到一個10 int的數組,然後可以在其上使用數組語法。

2

使用followi NG表達式語句

Test[0][0] = *ptr1; 

類型表達Test[0]的是int [10]。所以Test[0][0]將有類型int*ptr1的類型是int當然PTR1應具有可提領的有效值。