2016-04-21 52 views
0

請協助以下關於數組指針的問題。我有20個數組,每個數組長350個元素。我需要將20個數組中的3個地址傳遞給一個指針數組。 然後在我的代碼中,我需要訪問數組內的指針數組內的各個元素。但是我不確定語法,請評論下面的內容是否正確。將數組傳遞到C中的指針數組中

unsigned short  Graph1[350]; 
unsigned short  Graph2[350]; 
unsigned short  Graph3[350]; 
...  ...   ... 
unsigned short  Graph19 [350]; 
unsigned short  Graph20 [350]; 
unsigned short  *ptr_Array[3]; 
... 
*ptr_Array[0] = &Graph6; // Passing the address of array Graph6, into the array of pointers. 
*ptr_Array[1] = &Graph11; // Passing the address of array Graph11, into the array of pointers. 
*ptr_Array[2] = &Graph14; // Passing the address of array Graph14, into the array of pointers. 
... 
Varriable1 = *ptr_Array[1]+55 // Trying to pass the 55th element of Graph11 into Varriable1. 
+3

不是一個答案:'20個數組,每個350個元素'爲什麼你不使用二維數組? –

+0

數組本身應該是一個指針,不是嗎? – Rolice

+0

@Roice數組不是一個指針。如果用於表達式或作爲參數傳遞給函數,它會耗盡指針。 –

回答

2

表達*ptr_Array[1]+55是錯多次,因爲operator precedence

編譯器將其視爲(*(ptr_Array[1]))+55,即它需要ptr_Array中的第二個指針並將其取消引用以獲取第一個值,並將55添加到該值,而這不是您想要的值。您需要明確使用括號*(ptr_Array[1]+55)。或簡單地ptr_Array[1][55]


你應該真的考慮Mohit Jain的評論。而不是有20個不同的變量,只需使用一個:

unsigned short Graph[20][350]; 
2

*ptr_Array[0] = &Graph6;是錯誤的。它應該是:

ptr_Array[0] = Graph6; /* or &Graph6[0] */ 

ptr_Array類型爲array 3 of pointer to unsigned shortptr_Array[0]pointer to unsigned short*ptr_Array類型unsigned short

Graph6類型是array 350 of unsigned short如果在表達式中使用,這將耗盡pointer to unsigned short


Varriable1 = *ptr_Array[1]+55也是錯誤的。爲了通過55 元件,使用

Varriable1 = ptr_Array[1][55]; 
+1

'&Graph6'錯誤的一個原因是'&Graph6'的類型是'unsigned short(*)[350]'(指向350'unsigned short'的數組的指針),而'ptr_Array'的每個元素都是爲了是一個'unsigned short *',這兩種類型明顯不同 - 這就是編譯器抱怨指針類型不匹配的原因。 –

+0

'Varriable1 = * ptr_Array [1] [55];'應該'Varriable1 = ptr_Array [1] [55];' –

+0

@RishikeshRaje你是對的,謝謝。 –