C访问多维数组

时间:2013-02-19 04:58:18

标签: c arrays pointers multidimensional-array

尝试此操作时,我收到了一个下载编译器错误:

int **arrays;
// allocate and initialize it....
int pos1 = 0;
int pos2 = 1;
int value = (*arrays[pos1])[pos2];

如果括号中的部分取消引用int*指针,为什么数组访问不合法?

3 个答案:

答案 0 :(得分:3)

括号中的部分是int。首先,arrays[pos1]会产生一个指针(int*),然后您将其解除引用(通过预先固定的*运算符)。因此,(*arrays[pos1])是一个简单的int,而不是指针。

如果您的目标只是访问多维数组中的位置,请忘记*并使用:

arrays[pos1][pos2]

答案 1 :(得分:2)

麻烦在以下一行:

int value = (*arrays[pos1])[pos2];

您有int **arrays[pos1]使其成为int *,您可以通过*arrays[pos1]进一步解除引用,因此当您执行(*arrays[pos1])[pos2]时,{ {1}}是(*arrays[pos1]),而不是int会导致错误。

你可以做到

int*

答案 2 :(得分:0)

放置值(渐变)然后跟踪求和的方法。 要使阵列运行,是一个带括号的真正运动。也许hirarchical订购。是

带有结构符号{}的FOR循环,包含数学结果符号[] []。正是FOR循环生成数组Display!

边缘相对较小,以获得合适的设置或完全的胡言乱语。目标是将信息存储在2D阵列中。将新信息放入其中,稍后访问该信息槽。 我想尝试一下它的乐趣,看看逻辑兽是如何回应的。它说,在1000小时的训练范围内,你应该有一种感觉:)

   #include <stdio.h>
   int main()
   //2D_Array. Multilist. Sumline and Total Sum .
   //Select each coordinate by pressing ENTER after each number .
   //KHO2016.no7. mingw (TDM-GCC-32) . c-ansi .
   {
   //declare, valuate
   int a,b,c=1,d=1,i,j,k,l,sum0=0;
   int ar_a[20][20];

   //calculate
   jump0:
   for (l=0;l<1;l++)                // vary the value l<1 - l<10
   {printf ("M.M.M Shelf %d\n",l); // SHELF2
   for (k=0;k<1;k++)              // SHELF1
   {printf ("SumLine%d = %d\n",k,sum0);
   {for (i=1;i<6;i++)           // COLUMS .
   for (j=0;j<1;j++)           // LINES . per COLUM 
   {ar_a[i][j]=d*c++;         // put value into 2D_array indevidual result slot.
   sum0=sum0+(ar_a[i][j]);
   printf ("%d%d(%.2d*%.2d=%.3d)\t",i,j,d,c-1,ar_a[i][j]);}}}}

   printf ("TOTAL SUM = %d . Select 2 coordinates [1-5] enter, [0] enter: \n",sum0);
   scanf ("%d%d",&a,&b);
   printf ("You selected : %d and %d . Result value = %d\n",a,b,ar_a[a][b]);
   goto jump0;

   //terminate
   return 0;
   }