3

Why is address operator not needed for stud->names.firstName? But address operator is required in &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
}
halfelf
  • 9,737
  • 13
  • 54
  • 63
Keenlearner
  • 704
  • 1
  • 7
  • 21
  • 1
    Possible duplicate of [Why does scanf() need & operator in some cases, and not others?](http://stackoverflow.com/questions/3440406/why-does-scanf-need-operator-in-some-cases-and-not-others) – Raymond Chen Sep 29 '16 at 03:29

1 Answers1

4

It's not only not needed, it would be incorrect. Because arrays1 are automatically converted to pointers.

The following

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

is equivalent to

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

so using the address of operator here is redundant because both expressions are equivalent.

Using it like you do for the "%d" format specifier
(THIS IS WRONG)

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

would be wrong and actually undefined behavior would occur.

NOTE: Always verify the value returned from scanf().


1Also known as the array name

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Why would it be wrong to take the address? Since `firstName` is an array, I would expect it to work. It wouldn't work if `firstName` were a pointer, though. – Roland Illig Sep 29 '16 at 06:24
  • @RolandIllig It is equivalent to taking the address of a pointer. The important difference is that pointer arithmetics will be different. – Iharob Al Asimi Sep 29 '16 at 12:01