mri*_*dra 6 c malloc structure
建立一个结构并给它三个这样的成员,
struct student{
int rollno;
char name[10];
int arr[];
}stud1, stud2;
Run Code Online (Sandbox Code Playgroud)
现在给stud1提供4条记录,给stud2提供5条记录.我告诉面试官我们必须给数组一些大小,否则它不会被分配任何空间,否则会给编译错误.他说根据C的新标准,这是可能的.最后我无法理解如何去做.有人有建议吗?我试图做一个realloc,但我不确定自己是否会起作用.
样本本身是错误的,因为无法声明自动对象(stud1和stud2).但你可以写
struct student *s = malloc(sizeof *s + number_of_arr_elems * sizeof s->arr[0]);
Run Code Online (Sandbox Code Playgroud)