2017-01-15 22 views
1

在C++中的引物第5版,第3.5節,第115頁,它提供了以下示例:C++底漆 - 指針和引用到一個Array

int *ptrs[10]; // ptrs is an array of ten pointers to int 
int &refs[10] = /* ? */; // error: no arrays of references 
int (*Parray)[10] = &arr; // Parray points to an array of ten ints 
int (&arrRef)[10] = arr; // arrRef refers to an array of ten ints 

我理解幾乎所有的exemples,除了一個:

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

指向一個數組,我可以這樣做:

int a[10]; 
int *p = a; 

由於名稱「一」也是一個點呃到數組,現在p指向與由名稱'a'表示的指針相同的地方。

我試圖編譯經書給出的例子,我期待的是使用:

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

將有相同的效果,在我給的例子。問題是,沒有發生,這裏是代碼:

#include <iostream> 

using namespace std; 

int main(int argc, char const *argv[]) { 

    int arr[10] = {1,1,1,1,1,1,1,1,1,1}; 
    int *ptrs[10]; 
    int (*Parray)[10] = &arr; 
    int (&arrRef)[10] = arr; 

    cout << *(Parray + 1) << endl; 
    cout << Parray[1] << endl; 

    return 0; 
} 

此代碼編譯,並給出了下面的輸出:

0x7fff5c4a2ab8 
0x7fff5c4a2ab8 

有人能準確解釋:

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

是?我能用它做什麼?

回答

1

有人能準確解釋:

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

是什麼?我能用它做什麼?

類型的Parrayint (*)[10],這意味着它只能被分配給指針int [10]類型的對象。

所以,你有什麼是一個指向10個元素的數組的開始(由&arr獲得)的指針。

並通過Parray訪問的arr元素的方式會要求你先取消引用指針Parray獲得arr,你可以索引:

因此做

(*Parray)[5] = 546; 

分配第五元素爲546,從而導致下面的表達式會做什麼。

arr[5] = 546; 

如所見here

1

它只是指向具有某些元素的數組的指針。 你寫過,你可以簡單地使用指針int *p = a;這是正確的,但是這個指針不僅可以指向某個數組。技術上指針p指向數組中第一個元素的第一個地址。因爲靜態數組簽名是T(&)[N],所以只能指向10個元素的數組。使用數組簽名 你可以寫例如方法,它可以返回靜態數組的大小:

template < size_t N, typename T > size_t GetSize(T(&)[N]) 
{ 
    return N; 
} 
... 
int arr[10] = { 1,1,1,1,1,1,1,1,1,1 }; 
auto sz = GetSize(arr); 

如果你想用指針來工作,你可以以不同的方式使用它,但INT(* Parray2)如果你想看到數組的地址的區別,你可以得到的粒子陣列的地址,地址

int arr[10] = { 1,1,1,1,1,1,1,1,1,1 }; 
int arr2[11] = { 1,1,1,1,1,1,1,1,1,1,1 }; 

int *bare_ptr1 = arr; // legal 
int *bare_ptr2 = new int(); // legal 
int *bare_ptr3 = arr2; // legal 

int(*Parray)[10] = &arr; // legal 
int(*Parray2)[10] = new int(); // compile error 
int(*Parray3)[10] = arr2; // compile error 

cout << bare_ptr1 << endl; 
cout << &arr[0] << endl; 
cout << *(Parray + 0) << endl; 
cout << Parray[0] << endl; 

:10]只能指向數組有10個元素。這些地址必須不同。

cout << &Parray << endl; // address of the pointer which points to the array 
cout << &arr << endl; // addres of the first element in the array