2

I have come across an array with only one element. This array is defined inside a structure. Which goes like this:

typedef struct abc
{
    int variable1;
    char variable2;
    float array[1];
};

I don't understand why this array is required, why can't we define just a variable or define a pointer(considering array property).

I want to use it. How do i use this variable? abc.array[0] seems correct. Isn't it.

Addition I am not using any dynamic memory allocation then what is its significance ?

Vishwajeet Vishu
  • 492
  • 3
  • 16

1 Answers1

4

It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats.

The dynamic array has to be the last element.

Use like this:

struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float));
ptr->variable1 = N; /* usually store length somewhere in struct*/
Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18