Andrey Solovyov Andrey Solovyov - 4 months ago 10
C Question

Passing typedefed two-dimensional array of structs as function argument

I am write a tetris clone for Arduino.
In my implementation, I have a

struct
representing a point on screen:

struct tt_point
{
int x;
int y;
};


Each figure is an array of its rotation 'snaphots' or 'frames'. Each frame is an array of
tt_points
, which makes a figure a two-dimensional array of
tt_points
(you may find it ugly, but the question is not about design).

I'd like to typedef this two dimensional array and pass it to a function. Here is the typedef I have:

typedef tt_point tt_figure[4][4];


And a 'T' figure:

tt_figure tt_T = {
{{0,0}, {0,1}, {0,2},
{1,1}},

{{0,1},
{1,0}, {1,1},
{2,1}},

{{0,1},
{1,0}, {1,1}, {1,2}},

{{0,0},
{1,0}, {1,1},
{2,0}}
};


Problems begin when I try to pass a figure to a function:

void tt_drawFigure(tt_figure figure) { ... }


The error is:

Tetris:20: error: variable or field 'tt_drawFigure' declared void
Tetris:20: error: 'tt_figure' was not declared in this scope


How should I rewrite the declaration to pass a
tt_figure
to a function?

P.S. I made it working by declaring a figure as
void*
and then casting to 4x4 array:

void tt_drawFigure(void* figure)
{
tt_point * fig = ((tt_point(*)[4]) figure)[frame_index];
...
}


But there should be a nicer way.

UPDATE.
The code you can copy, paste and try to compile:

struct tt_point
{
int x;
int y;
};

typedef tt_point tt_figure[4][4];

tt_figure tt_T = {
{{0,0}, {0,1}, {0,2},
{1,1}},

{{0,1},
{1,0}, {1,1},
{2,1}},

{{0,1},
{1,0}, {1,1}, {1,2}},

{{0,0},
{1,0}, {1,1},
{2,0}}
};


void setup()
{

}


void loop()
{

}

void tt_drawFigure(tt_figure figure)
{

}

sps sps
Answer

Your code compiles if you change typedef tt_point tt_figure[4][4]; to typedef struct tt_point tt_figure[4][4];. For example this code below compiles and runs fine.

#include<stdio.h>
struct tt_point
{
    int x;
    int y;
};

/* typedef tt_point tt_figure[4][4]; /* // Issue here
typedef struct tt_point tt_figure[4][4]; // add `struct' to typedef

void tt_drawFigure(tt_figure figure);

tt_figure tt_T = { {{0,0}, {0,1}, {0,2}, {1,1}},
                   {{0,1}, {1,0}, {1,1},{2,1}},
                   {{0,1}, {1,0}, {1,1},{1,2}},
                   {{0,0}, {1,0},{1,1}, {2,0}}
                 };

int main(void)
{
    tt_drawFigure(tt_T);
    return 0;
}

void tt_drawFigure(tt_figure figure)
{ 
    int i, j;

    for (i = 0; i < 4; i++) {
            for (j = 0; j < 4; j++)
                    printf("%d, %d --- ", figure[i][j].x, figure[i][j].y);
            printf("\n");
    }
    /* Do your drawing */
}

You can also do

typedef struct tt_point
{
    int x;
    int y;
} tt_figure[4][4];

so that you dont accidentally miss struct - like you missed when you did a typedef separetely.