Array of structure contiguous in memory

I would like to create an array of structure with a dynamic array:

typedef struct{
    float a;
    int b[];
}structure_t;

  n = ...;
  size_t dimstruct = sizeof(structure_t)+n*sizeof(int);
  structure_t * resultat = malloc(dimstruct);

      

How do I create a dynamic array of this structure and contiguous in memory?

thank!

+3


source to share


1 answer


You have the right idea. The code you wrote allocates space for a single structure with a variable size array using a C99 style flex item. The same trick will work with a C90-style zero-length array or 1-dimensional array .

The structure usually includes a member to indicate the size of the variable-length part, although this is obviously not a requirement. But you can see how it is a problem to create an array of these structures.

At all

structure_t my_array[5];
...
my_array[2].a = 0.0;

      

coincides with

(structure_t*)((void*)my_array + 2*sizeof(structure_t))->a = 0.0;

      



But what is sizeof

our dynamic structure? Whatever happens to be evaluated, this is clearly what we want as it does not include the variable part.

So, we can allocate an array of these structures by doing

void *result = malloc(arraysize * dimstruct);

      

and it will be contiguous. But we cannot use the array indexing syntax, since the size of the structure is undefined. Instead, we index manually as above:

structure_t *p = result + i * dimstruct;
p->a = 0.0;

      

Please note that result

is void *

. If we declared it as structure_t *

, the offset calculation would be wrong, as it would use multiplessizeof(structure_t)

0


source







All Articles