1

I have a structure with a 2d array. I'm passing a pointer to this structure to a function, where I need to edit the 2d array. I am struggling to find the correct syntax to reference the 2d array from within my function.

#define TG_WIDTH 10
#define TG_HEIGHT 20

typedef enum {
   BLOCK_T = 0,
   BLOCK_LINE,
   BLOCK_SQUARE,
   BLOCK_L,
   BLOCK_L_REVERSE,
   BLOCK_S,
   BLOCK_S_REVERSE
} block_t;

typedef struct {
   char y_max[TG_WIDTH];
   block_t grid[TG_WIDTH][TG_HEIGHT];
} scratchpad_t;

bool
placeBlock(scratchpad_t *sp) {
   block_t (*g)[TG_WIDTH] = sp->grid;

   g[1][2] = BLOCK_T;
}

This gives me an "initialization from incompatible pointer type" warning though. What is the correct way to define/initialize "g" here?

2 Answers 2

3

Change TG_WIDTH to TG_HEIGHT:

block_t (*g)[TG_HEIGHT] = sp->grid;
Sign up to request clarification or add additional context in comments.

Comments

2

What's wrong with the simplest possible?

sp->grid[1][2] = BLOCK_T;

If you have many array accesses in your function and you want to factor out sp->grid because you think this will be faster (fewer dereferences), I think that all optimizing C compilers take care of that pretty well.

3 Comments

I'm porting a perl script to C and in the perl script I had used the g[1][2] syntax everywhere so that is what led me in this direction. Your solution works though...I should have thought of that :)
I'm still curious as to what the syntax should be for the way I was trying to do it originally
You already had it, just switched the dimensions... :-) It is block_t (*g)[TG_HEIGHT] = sp->grid; (a pointer, i.e. an array, of arrays of blocks, each of which having TG_HEIGHT elements). Somebody answered it but deleted his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.