Home »
C programming language
Missing ampersand/address of (&) in scanf() (C language Error)
In this article, we are going to learn about an error which occurs in C programming language when we miss to use ampersand/address of operator while using scanf() function.
Submitted by IncludeHelp, on May 15, 2018
Missing ampersand/address of (&) in scanf() (C language Error)
This is a very common mistake made by the programmers, while reading values using scanf(), we give the variable name but sometimes we forget to use ampersand/address of operator (&) with the scanf() function.
Note: It is not required to use ampersand/address of (&) operator always with the scanf() function. While using pointers and reading string (character array) values, we do not use it.
The arguments of the scanf() function are the pointers types, we must provide either an address of a variable or a pointer (which contains the address of the variable).
Therefore, if we are using a pointer in scanf(), we don’t use address of (&) operator, because pointer contains the address itself.
Thus, the following statement will be wrong:
int age; char gender;
scanf("%c%d",gender, age);
Here, gender and age are the normal variables that are used to store, retrieve the values that means age and gender will work with the values only, and scanf() needs address of the variables. So, the above written statement will be wrong.
Then, what will the correct statement?
Here is the correct statement to read ‘gender’ and ‘age’ through scanf()...
int age; char gender;
scanf("%c%d",&gender, &ge);
We can also use the pointers, as scanf() accepts addresses,
Thus, this statement will also be correct:
//variable declarations
int age; char gender;
//pointer declarations and assignment
int *ptr_age = &age; char *ptr_gender = &gender;
scanf("%c%d",ptr_gender, ptr_age);
Example to read age and gender in C:
#include <stdio.h>
int main()
{
//variable declarations
int age; char gender;
//input values
printf("Enter gender, age (separate by space): ");
scanf("%c%d",&gender,&age);
printf("Gender: %c, Age: %d\n",gender,age);
return 0;
}
Output
Enter gender, age (separate by space): M 29
Gender: M, Age: 29