I'm currently trying to understand how to implement a 2-dimensional array of struct in C. My code is crashing all the time and I'm really about to let it end like all my approaches getting firm to C: garbage. This is what I got:
typedef struct {
int i;
} test;
test* t[20][20];
*t = (test*) malloc(sizeof(test) * 20 * 20);
My glorious error:
error: incompatible types when assigning to type ‘struct test *[20]’ from type ‘struct test *’
Do I have to allocate the memory seperately for every 2nd dimension? I'm getting nuts. It should be so simple. One day I will build a time-machine and magnetize some c-compiler-floppies...
We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.
A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. Many games use two dimensional arrays to plot the visual environment of a game.
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure.
This should be enough:
typedef struct {
int i;
} test;
test t[20][20];
That will declare a 2-dimensional array of test
of size 20 x 20. There's no need to use malloc.
If you want to dynamically allocate your array you can do this:
// in a function of course
test **t = (test **)malloc(20 * sizeof(test *));
for (i = 0; i < 20; ++i)
t[i] = (test *)malloc(20 * sizeof(test));
test **t;
t = (test **)malloc(sizeof(test *) * 20);
for (i = 0; i < 20; i++) {
t[i] = (test *)malloc(sizeof(test) * 20);
}
Other answers show how to fix it but they don't explain why. As the compiler hinted, the type of t
in your original example is actually test *[20]
which is why your cast to test *
wasn't enough.
In C, the name of an array T of dimension N is actually of type *T[dim0][dim1]...[dimN-1]
. Fun.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With