I assume this is basic question, but I’m not English and not used still with the terms of programming language, that’s why I question here (I couldn’t find).
Here’s my context:
I have a structure (let’s simplify it) as follow
struct _unit
{
char value;
} Unit;
and in the main program, I’d like to have a row of pointers that points a row of other pointers pointing structures Unit.
Something like
int main ()
{
Unit** units;
..
printf("%d", units[0][0].value);
...
}
I get a little confused, what is the way to go so Unit‘s can be accessed as a multi-dimensional array.
here’s my try
{
units = (Unit**)malloc(sizeof(void*));
units[0][0] = (Unit*)malloc(sizeof(Unit));
}
You’re almost there.
First, you need to declare your type, as you have, as
Unit**. Then, on that, allocate enoughUnit*pointers to hold the number of rows. Finally, loop over those created pointers, creating eachUnit.For example:
That’s the traditional way of doing it. C99 also introduced a different syntax to do this, as follows:
From: https://stackoverflow.com/a/12805980/235700