- 2069 Asar · 4 marks
scanf with %s and no ampersand
Short answer
In scanf, the array name str is already the address of its first element, so & is unnecessary. The %s specifier stops reading at whitespace, so strings with spaces cannot be entered; use %[^\n] or fgets instead.
Consider a statement
scanf("%s",str);
Where str is a string variable. In above statement, why '&' symbol is not used? Can we input string with space in this statement? If not, why?
Why & is not used
In scanf("%s", str), str is the name of a character array, and the name of an array is already the address of its first element. scanf needs the address of the place where the value is to be stored, so the array name alone is enough. Writing &str is not needed (it has the same address but a different type). For ordinary variables like int n, the address must be given explicitly as &n.
Can a string with spaces be entered?
No. %s reads characters until the first white-space (space, tab or new line) and stores only that word. The rest stays in the input buffer.
#include <stdio.h>
int main(void)
{
char str[40];
printf("Enter a string: ");
scanf("%s", str); /* no & : str is already an address */
printf("Stored: %s\n", str);
return 0;
}
Input Kathmandu Valley gives:
Enter a string: Stored: Kathmandu
To read a string with spaces use a scan set %[^\n], or fgets:
#include <stdio.h>
int main(void)
{
char str[40];
scanf("%39[^\n]", str); /* reads a line including spaces */
printf("Stored: %s\n", str);
return 0;
}
Output for the same input:
Stored: Kathmandu Valley
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Insert a string into another string · Computer Programming, chapter 7
- Employees with salary above 10,000 · Computer Programming, chapter 8
- Nested if with flowchart · Computer Programming, chapter 5
- Conditional operator vs if-else; digit sum · Computer Programming, chapter 5
- Switch statement in decision making · Computer Programming, chapter 5
- Syntax of if...else · Computer Programming, chapter 5
- Space switch and why TST is used · Telecommunications, chapter 4
- RA: employee-projects with no part used · Database Management System, chapter 3
- Random process; LTI output is WSS if input is WSS · Communication Systems, chapter 9
- Voltage across string discs is not uniform · Power System Analysis I, chapter 2 · asked 3×