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

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): ");

	printf("Gender: %c, Age: %d\n",gender,age);
	return 0;


    Enter gender, age (separate by space): M 29
    Gender: M, Age: 29


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.