What is the reason for the flexible element of the array not at the end of the structure error?

I am wondering why I keep getting the error error: flexible array member not at end of struct when calling malloc. I have a structure with a variable length array, and I keep getting this error.

Structure is

 typedef struct { size_t N; double data[]; int label[]; } s_col; 

and the malloc call is

 col = malloc(sizeof(s_col) + lc * (sizeof(double) + sizeof(int))); 

Is this a malloc call right?

+8
c struct malloc
source share
3 answers

You can have only one flexible member of the array in the structure, and it should always be the last member of the structure. In other words, in this case, you made a mistake before you call malloc , to such an extent that there really is no way to correctly call malloc for this structure.

To do what you think is needed (arrays of the same number of data and label members), you can consider something like:

 struct my_pair { double data; int label; }; typedef struct { size_t N; struct my_pair data_label[]; }; 

Note that this is somewhat different: instead of a double array followed by an int s array, it gives an array of one double , followed by one int , then the next double , then int , etc. Whether it will be close enough to the same or not will depend on how you use the data (for example, to move to an external function that expects a continuous array, you will probably have to do something different).

+14
source share
 typedef struct { size_t N; double data[]; int label[]; } s_col; 

You cannot flexible array element ( double data[] ) in the middle. Consider the size of a hard-set array or double *data

+3
source share

Given the definition of the structure and a pointer to the beginning of the structure, it is necessary that the C compiler can access any member of the structure without the need for access to anything else. Since the location of each element in the structure is determined by the number and types of elements preceding it, to access any element you need to know the number and types of all previous elements. In the particular case when the last element is an array, this does not create any special difficulties, since accessing an element in an array requires knowing its beginning (which requires knowing the number and type of previous elements, and not the number of elements in the array) and the index of the element (which is the compiler can be considered smaller than the number of elements for which space exists, without the need to know anything about the size of the array). If a Flexible Array element appears anywhere except at the end of the structure, the location of any elements that follow it will depend on the number of elements in the array - something that the compiler will not recognize.

+2
source share

All Articles