Make a structure and give it three members like this,
struct student{
int rollno;
char name[10];
int arr[];
}stud1, stud2;
now give 4 records of marks to stud1, and 5 records of marks to stud2. I told the interviewer that we have to give array some size otherwise it is not going to be assigned any space , or it would give compiler error. He said according to new standards of C , it is possible. Finally i couldn't understand how to do it.Do anyone have suggestions ? I tried to do a realloc but i was not sure myself if it would work.
The sample itself is wrong because automatic objects (stud1 and stud2) can not be declared. But you can write
struct student *s = malloc(sizeof *s + number_of_arr_elems * sizeof s->arr[0]);
It's a flexible array member. This feature has been added in C99. It allows the last member of a structure type to have an incomplete array type. This feature is explained in 6.7.2.1 in C99 Standard.
"As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. [...]"
The rest of the paragraph describes its usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With