问题描述
为什么螺柱->names.FirstName不需要地址运算符? 但在&;Studd->Studentid?中需要地址运算符?struct student {
struct
{
char lastName[10];
char firstName[10];
} names;
int studentid;
};
int main()
{
struct student record;
GetStudentName(&record);
return 0;
}
void GetStudentName(struct student *stud)
{
printf("Enter first name: ");
scanf("%s", stud->names.firstName); //address operator not needed
printf("Enter student id: ");
scanf("%d", &stud->studentid); //address operator needed
}
推荐答案
它不仅是不需要的,而且是不正确的。因为数组1会自动转换为指针。
以下
scanf("%s", stud->names.firstName);
相当于
scanf("%s", &stud->names.firstName[0]);
因此在此处使用运算符的地址是多余的,因为这两个表达式是等价的。
像使用"%d"
格式说明符一样使用它
(这是错误的)
scanf("%s", &stud->names.firstName);
将是错误的,并且实际上将发生未定义的行为。
注意:始终验证scanf()
返回的值。
1也称为数组名称