2016-09-29 70 views
3

为什么地址运算符不需要stud-> names.firstName? 但是需要地址运算符& stud-> studentid?为什么在scanf中不需要address操作符?

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()的需要和在某些情况下,运营商,而不是其他人?](HTTP可能重复://计算器.com/questions/3440406/why-does-scanf-need-operator-in-some-cases-and-not-others) –

回答

4

这不仅是不需要的,它是不正确的。因为阵列会自动转换为指针。

以下

scanf("%s", stud->names.firstName); 

相当于

scanf("%s", &stud->names.firstName[0]); 

所以使用运营商这里的地址是多余的,因为两个表达式是等效的。

使用它就像你的"%d"格式说明
做(这是错误

scanf("%s", &stud->names.firstName); 

将是错误的,实际上会发生未定义的行为。

备注:始终验证从scanf()返回的值。


又称数组名

+0

为什么要采取这个地址是错误的?由于'firstName'是一个数组,我期望它能够工作。但是,如果'firstName'是一个指针,它将不起作用。 –

+0

@RolandIllig它相当于取指针的地址。最重要的区别是指针算术会有所不同。 –

相关问题