下面的描述中,( )不能正确定义一个名为 Student 的结构体以及一个包含 $20$ 个元素的结构数组。
A.
struct Student {
string name;
int age;
float score;
};
struct Student students[20];B.
struct Student {
string name;
int age;
float score;
};
Student students[20];C.
struct Student {
string name;
int age;
float score;
};
Student* students = new Student[20];D.
struct Student {
string name;
int age;
float score;
};
Student students = new Student[20];答案D。数组作为函数参数时退化为指针,参数中int a[]等价于int* a。二维数组的第二维必须指定。
数组下标从0开始!长度为n的数组下标范围是0~n-1,访问a[n]越界!
【考点】结构体定义|数组声明|指针赋值
命题人卡住考生对动态数组与静态数组语法混用的边界认知,这是C++基础语法中最易混淆的陷阱区。四级大纲明确要求掌握struct定义及数组声明,D选项正是利用考生对new返回类型的不熟悉,混淆了结构体变量与指针的语法差异。
看到new Student[20]先想返回类型是Student*。若students声明为Student类型,则类型不匹配,编译器直接报错。正确做法是声明Student* students或直接用数组下标访问。这一类题通法是:检查赋值左右两边的类型是否兼容,尤其注意new返回的是指针。对于结构体数组,静态声明Student students[20]和动态声明Student* students = new Student[20]都是合法的,但必须确保类型匹配。
选项D最阴险:new Student[20]返回指针,却赋值给Student students。命题人利用考生对new语义的模糊化(误以为new可以像普通变量赋值),以及C++类型系统严格的检查机制。若只背"可以用new分配数组"而不理解返回类型,必选D。AB是标准数组声明,C是动态数组正确用法,均无陷阱。
若将D改为Student* students = new Student[20];则正确;若题目要求必须用静态数组,则C错。刷到类似题先问:新类型下new返回什么?变量声明是什么?两者是否匹配?命题人可能把new换成malloc,或把Student换成int,考察类型匹配的本质。