Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a 2-dimensional array of struct in C

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...

like image 440
PenthousePauper Avatar asked Jul 18 '10 11:07

PenthousePauper


People also ask

How do you declare a 2D array in structure?

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.

What is two-dimensional array in data structure with example?

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.

Is it possible to have a struct with arrays?

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.


3 Answers

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));
like image 175
IVlad Avatar answered Oct 09 '22 19:10

IVlad


test **t;

t = (test **)malloc(sizeof(test *) * 20);
for (i = 0; i < 20; i++) {
   t[i] = (test *)malloc(sizeof(test) * 20);
}
like image 10
BobTurbo Avatar answered Oct 09 '22 18:10

BobTurbo


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.

like image 4
msw Avatar answered Oct 09 '22 17:10

msw