为什么scanf中不需要地址运算符? [英] Why is address operator not needed in scanf?
本文介绍了为什么scanf中不需要地址运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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也称为数组名称
这篇关于为什么scanf中不需要地址运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文