bgroenks
bgroenks

Reputation: 1889

C Access Multi-Dimensional Array

I'm getting a subscripting compiler error when trying this:

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

If the part in parentheses dereferences to a int* pointer, why would the array access not be legal?

Upvotes: 1

Views: 698

Answers (3)

Radar Blue
Radar Blue

Reputation: 1

A way to put a value (gradient) and then trace sumlines. To get the array to behave, is a real excercise with brackets. Maybe hirarchical ordered. Being of

FOR loops with structural symbol { }, containing math result symbol [ ][ ]. It is the FOR loops that generate the array Display !

The margins are relatively small, to obtain a decent setup or complete gibberish. The objective is to have information stored in a 2D array. Put new information in there, and get access to that information slots later. Im trying to have some fun with it, and see how the logic beast responds. Its said that in the range 1000 hours of training, you should get a feeling for it :)

   #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;
   }

Upvotes: 0

Jay
Jay

Reputation: 24905

The trouble is in the below line:

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

You have an int **, arrays[pos1] makes it an int *, which you are further dereferencing by doing *arrays[pos1], so when you do (*arrays[pos1])[pos2], (*arrays[pos1]) is an int and not int* which causes the error.

You can just do

int value = arrays[pos1][pos2];

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37928

The part in parentheses is an int. Firstly, arrays[pos1] yields a pointer (int*), that you then have dereferenced (via the pre-fixed * operator). Thus, (*arrays[pos1]) is a simple int, and not a pointer.

If your goal is simply to access a position with in a multi-dimensional array, forget the * and just use:

arrays[pos1][pos2]

Upvotes: 3

Related Questions