Mike Xydas
Mike Xydas

Reputation: 489

Accesing values on a 2d struct array

So I have this struct

struct cell
{
    int downwall;
    int rightwall;
};

I have dynamically allocated memory for a 2d array of struct cell (struct cell ** array)

However when I try to access a certain cell with the command

array[i][j] -> downwall = 0;

I get this error:

invalid type argument of '->' (have 'struct cell')

Upvotes: 2

Views: 84

Answers (5)

Fenn-CS
Fenn-CS

Reputation: 905

Your struct is not a pointer struct so simply do something like:

//array cells of type cell and can hold 10 cell's
struct cell cells[10];

//Try using malloc for memory allocation
 cells[0] = (struct cell *) malloc(sizeof(struct cell));  

//example assignment
cells[0].downwall=0;
cells[0].rightwall=1;

Upvotes: 0

nerez
nerez

Reputation: 447

Please note that

struct cell** array

is not a 2D array! it is a pointer to a pointer of type 'struct cell'. You should regard it as a 2D array only if there is an allocated memory to which the values point (Statically or dynamically). Otherwise, you are on the road for a Segmentation Faults.

Upvotes: 0

Arif Burhan
Arif Burhan

Reputation: 505

You need to declare an actual array with the right number of indices, then make the pointer point to it. Use typed names to help ( simplified Hungarian Notation )

 int    iAry[M][N];
 int    **ptrAry;

 ptrAry = iAry;    /*  equivalent to ptrAry = &iAry[0][0];    */

 /* then use -> operator as you have done   */

Upvotes: -2

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Use

array[i][j].downwall = 0;

instead.

You would have used -> if arrray[i][j] had type struct cell* which it doesn't have. It has type struct cell.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

The type of array[i][j] will be of struct cell, not struct cell *. You should use the . operator to access a member.

You need to write

 array[i][j].downwall = 0;   // use of .

Upvotes: 1

Related Questions