6

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.

mrigendra
  • 1,472
  • 3
  • 19
  • 33
  • 1
    I like the sharing. The question makes sense and is well connected to your experience. This kind of question will surely be appreciated by job-seekers :) – Rerito Oct 26 '13 at 16:58

2 Answers2

8

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]);
ensc
  • 6,704
  • 14
  • 22
  • But what was the need to give space like this, i mean a pointer inside the structure can also serve the purpose too.. – mrigendra Oct 26 '13 at 17:20
  • 1
    You will have to manage a second dynamic memory area then. E.g. now, you are done with 'free(s)'; a pointer needs an extra 'free(s->arr)'. Performance might be another reason because you need to allocate now two instead one object on heap. – ensc Oct 26 '13 at 17:28
3

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.

ouah
  • 142,963
  • 15
  • 272
  • 331