Why can not I enter values?


I can't input values without an error popping up, even though the code is correct.

#include <stdio.h>

int main()
    char name[100];
    printf("Enter your name: ");
    scanf_s("%s", name);
    printf("Your Name is: %s", name);
    return 0;

As soon as I input a value to the name and press enter, an error message pops up and says:

Unhandled exception at 0x0FC13FD4 (msvcr120d.dll) in Project8.exe: 0xC0000005: Access violation writing location 0x00D40000.

What is causing this and how can it be fixed?

Try this

if (scanf_s("%99s", name, _countof(name)) == 1)
    printf("Your Name is: %s", name);

Two things

  1. scanf_s() is a buffer overflow safe function, and it expects a length argument for "%s" specifier.

  2. You should only proceed to printf() if you actually succeeded scannig the value, for which the check (scanf(...) == 1) is there.

    The 1 there, means one of the input parameters matched by the specifiers, since in this case there is only one of them, then it will mean a full match.

Also, I am almost sure that the _countof() macro, is defined as sizeof(x) / sizeof(x[0]) so this should also do it

if (scanf_s("%99s", name, sizeof(name)) == 1)
    printf("Your Name is: %s", name);

since in this case sizeof(name[0]) == sizeof(char) == 1.

Your code could work if you used the standard scanf() function, i.e.

if (scanf("%99s", name) == 1)
    printf("Your Name is: %s", name);