I was in a technical interview and asked to create such a structure.

Create a structure and give it three elements as follows:

struct student{ int rollno; char name[10]; int arr[]; }stud1, stud2; 

now give 4 label entries on stud1 and 5 label entries on stud2. I told the interviewer that we must give an array of some size, otherwise it will not be assigned any space, or this will give a compiler error. He said that according to the new C standards, this is possible. Finally, I could not figure out how to do this. Anyone have any suggestions? I tried to realloc, but I was not sure if this would work.

+6
source share
2 answers

The pattern itself is erroneous because automatic objects (stud1 and stud2) cannot be declared. But you can write

 struct student *s = malloc(sizeof *s + number_of_arr_elems * sizeof s->arr[0]); 
+8
source

This is a flexible element of an array. This feature has been added in C99. It allows the last member of a structure type to have an incomplete array type. This function is explained in 6.7.2.1 in the C99 standard.

“As a special case, the last element of the structure with more than one named element may have an incomplete array type, which is called a flexible member of the array. [...]"

The rest of the paragraph describes its use.

+3
source

Source: https://habr.com/ru/post/956788/


All Articles