Keenlearner Keenlearner - 2 months ago 6
C Question

Why is address operator not needed in scanf?

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
}

Answer

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

Comments