2014-10-18 90 views
0

我是C++新手。請看下面的代碼:初始化指向數組C++的指針

//sample1 
int arr[2] = { 11, 22 }; 
int(*t)[2]; 
t = &arr; 
cout << *t[0] << "\n"; 
cout << *t[1] << "\n"; 


//sample2 
int arr2[2]; 
arr2[0] = { 33 }; 
arr2[1] = { 44 }; 
int(*t2)[2]; 
t2 = &arr2; 
cout << *t2[0] << "\n"; 
cout << *t2[1] << "\n"; 


//sample3 
int arr3[2]; 
arr3[0] = { 55 }; 
arr3[2] = { 66 }; 
int(*t3)[2]; 
t3 = &arr3; 
cout << *t3[0] << "\n"; 
cout << *t3[1] << "\n"; 

//輸出

11 
-858993460 
33 
-858993460 
55 
66 

誰能告訴我如何初始化一個指針數組樣本3超出了我的理解?

+2

這是錯誤的:'arr3 [2] = {66};' – 2014-10-18 14:45:16

+1

'arr'的初始化沒有任何問題。你應該閱讀'*'和'[]'運算符的優先級。 (提示:它應該是'(* arr)[0]'等) – 2014-10-18 14:45:43

回答

1

有兩個問題與您的代碼:

1)[]有更多的優先級比*所以你需要在所有這些情況下,括號(CFR operator precedence)。如果你不使用它們,你將在每個2個整數的數組上進行指針運算(因而立即超出範圍)。

int(*t)[2]; // A pointer to an array of 2 integers 
cout << t[0]; // The address of the array 

[first_integer][second_integer] ... garbage memory ... 
^ 

cout << t[1]; // The address of the array + sizeof(int[2]) 

[first_integer][second_integer] ... garbage memory ... 
          ^
cout << *t[0]; // Dereference at the address of the array 
cout << *t[1]; // Dereference past the end of the array 

// ---- correct ----- 

cout << (*t)[0]; // Dereference the pointer to the array and get the element there 

[first_integer][second_integer] ... garbage memory ... 
^ 

cout << (*t)[1]; // Dereference the pointer to the array and get the second element there 

[first_integer][second_integer] ... garbage memory ... 
      ^ 

2)你必須在行

arr3[2] = { 66 }; 

一個徹頭徹尾的程接入這是你應該如何進行:

//sample1 
int arr[2] = { 11, 22 }; 
int(*t)[2]; 
t = &arr; 
cout << (*t)[0] << "\n"; 
cout << (*t)[1] << "\n"; 


//sample2 
int arr2[2]; 
arr2[0] = { 33 }; 
arr2[1] = { 44 }; 
int(*t2)[2]; 
t2 = &arr2; 
cout << (*t2)[0] << "\n"; 
cout << (*t2)[1] << "\n"; 


//sample3 
int arr3[2]; 
arr3[0] = { 55 }; 
arr3[1] = { 66 }; 
int(*t3)[2]; 
t3 = &arr3; 
cout << (*t3)[0] << "\n"; 
cout << (*t3)[1] << "\n"; 

初始化就好了。

1

數組是幾乎同樣的事情作爲指針:

int arr[2] = { 11, 22 }; 
int * t; 
t = arr; 
cout << t[0] << "\n"; 
cout << t[1] << "\n"; 
0

在此代碼段

//sample3 
int arr3[2]; 
arr3[0] = { 55 }; 
arr3[2] = { 66 }; 
int(*t3)[2]; 
t3 = &arr3; 
cout << *t3[0] << "\n"; 
cout << *t3[1] << "\n"; 

有與兩個元件限定的陣列。指數此數組的元素的有效範圍是0, 1 在此語句

arr3[2] = { 66 }; 

有將數據寫入所述陣列之外,因爲索引2是無效的嘗試。所以,你必須

arr3: | 55 | uninitilaized | 66 | 
index: 0  1   beyond the array 

這些語句之後

int(*t3)[2]; 
t3 = &arr3; 

指針T3指向數組ARR3,

表達

t3[0] 

給陣列ARR3

表達

*t3[0] 

給出數組的第一個元素。因此,聲明

cout << *t3[0] << "\n"; 

輸出55。

表達

t3[1] 

指向的內存之後(超出)陣列ARR3。您在該地址的值66。寫了那麼這個值由聲明

cout << *t3[1] << "\n"; 

當然此代碼段是無效的outputed因爲沒有爲代碼的對象保留其覆蓋的內存。