0

I want to define a structure on the following way:

typedef struct Info_s
{
 uint8   Size;
 uint8   Address;
 uint8   Pattern[Size];    
}Info_t;

As you can notice the size of the array Pattern is "Size" which is declared first in the same structure.

Is that correct?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Stack Over
  • 425
  • 2
  • 8
  • 18

5 Answers5

5

An array declared as a struct field must either have an integer constant expression as its size or be a flexible array member with no size (uint8 Pattern[];). Your variant is neither.

If the array size in your case is a run-time value, you have two choices

  1. Flexible array member uint8 Pattern[];, which will result in a "flat" struct. The proper amount of memory to accommodate the entire struct with the array of desired length will have to be allocated with malloc manually.

  2. Pointer member uint8 *Pattern;, in which case your struct will become two-leveled. Memory for the struct itself and memory for the array will generally become two separate memory blocks allocated independently.

A flexible array member is typically a better idea (and matches your apparent original intent), unless you have some other requirements that would preclude that aproach.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2

You can't do that. That is violating the rule. Compile the code and you will know it clearly.

Rather keep a uint8* and then allocate to it memory (using malloc,realloc etc) based on the value of Size.

And now if you increase or decraese the value Size as per that reallocate your memory.

Yes with this, you have to free the dynamically allocated memory when you are done working with it.

user2736738
  • 30,591
  • 5
  • 42
  • 56
2

Just remove the array size Size in the declaration of Pattern and you will get a valid declaration of a structure with a flexible array member.:)

typedef struct Info_s
{
 uint8   Size;
 uint8   Address;
 uint8   Pattern[];    
}Info_t;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Go with

uint8*   Pattern;

and use malloc to allocate its size once Size is known.

sjsam
  • 21,411
  • 5
  • 55
  • 102
1

If you want to dynamically allocate memory to the structure, you can do it in following way :

struct Info_s
{
 uint8   Address;
 uint8   Pattern[Size];    
};

int main()
{
       struct Info_s *no;
       int i, noOfRecords;
       printf("Enter no: ");
       scanf("%d", &noOfRecords);

       no=(struct Info_s*) malloc (noOfRecords * sizeof(struct course));

       for(i=0;i<noOfRecords;++i)
       {
          scanf(...);
       }
     .
     .
     .
     return 0;
}

You can also refer https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation for more information.