c - 为什么 scanf 中不需要地址运算符?

标签 c pointers scanf

为什么 stud->names.firstName 不需要地址运算符? 但是 &stud->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也称为数组名

关于c - 为什么 scanf 中不需要地址运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760822/

相关文章:

c++ - 通过void指针修改结构体的内容

c - 使用 sscanf 将元素添加到每个索引的 int 数组中

c - scanf 被跳过

c - scanf不会第二次要求输入

c++ - 与执行随机快速排序相关的运行时错误

c - 为什么我的 void 指针会更改程序中的值?

c - 在 C 的参数中使用带有 shell 元字符的 execlp 系统调用

c++ - linux下练习编程的问题

python - ctypes指针问题

c++ - 当使用指向数组的指针时,我们迭代什么?