6

I wanted to scan and print a string in C using Visual Studio.

#include <stdio.h>

main() {
    char name[20];
    printf("Name: ");
    scanf_s("%s", name);
    printf("%s", name);
}

After I did this, it doesn't print the name. What could it be?

TheWitcher
  • 63
  • 1
  • 1
  • 4

1 Answers1

9

Quoting from the documentation of scanf_s,

Remarks:

[...]

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

So, the scanf_s

scanf_s("%s", &name);

is wrong because you did not pass a third argument denoting the size of the buffer. Also, &name evaluates to a pointer of type char(*)[20] which is different from what %s in the scanf_s expected(char*).

Fix the problems by using a third argument denoting the size of the buffer using sizeof or _countof and using name instead of &name:

scanf_s("%s", name, sizeof(name));

or

scanf_s("%s", name, _countof(name));

name is the name of an array and the name of an array "decays" to a pointer to its first element which is of type char*, just what %s in the scanf_s expected.

Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83