Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I was in a technical interview and asked to make a structure like this.. [duplicate]

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.

like image 911
mrigendra Avatar asked Oct 26 '13 16:10

mrigendra


2 Answers

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]);
like image 103
ensc Avatar answered Nov 15 '22 08:11

ensc


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.

like image 30
ouah Avatar answered Nov 15 '22 07:11

ouah