2016-04-21 60 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你是对的,谢谢。 –