3

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));
}
vdegenne
  • 12,272
  • 14
  • 80
  • 106

2 Answers2

4

You're almost there.

First, you need to declare your type, as you have, as Unit**. Then, on that, allocate enough Unit* pointers to hold the number of rows. Finally, loop over those created pointers, creating each Unit.

For example:

int i;
Unit** u;

// Allocate memory to store 50 pointers to your columns.    
u = malloc(sizeof(Unit*) * 50);

// Now, for each column, allocate 50 Units, one for each row.
for(i=0; i<50; i++) {
    u[i] = malloc(sizeof(Unit) * 50);
}

// You can now access using u[x][y];

That's the traditional way of doing it. C99 also introduced a different syntax to do this, as follows:

Unit (*u)[n] = malloc(sizeof(Unit[n][n])) // n = size of your matrix

From: https://stackoverflow.com/a/12805980/235700

Community
  • 1
  • 1
slugonamission
  • 9,562
  • 1
  • 34
  • 41
2

You may have misunderstood the meaning of the struct declaration.

struct _unit
{
    char value;
} Unit;

The effect of your code is to declare a struct type struct _unit and allocate space for one variable of that type, named Unit.

What you probably meant to say is

struct _unit
{
    char value;
};

typedef struct _unit Unit;

In C, the word "struct" is part of the type unless you typedef it.

jforberg
  • 6,537
  • 3
  • 29
  • 47