Skip to main content

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)

All Computer Programming chapter 4 questions →