2

According to the book: How to C Programming - Eighth Edition (by Deitel brothers) this code reads the word "Hello":

#define SIZE 20

int main()
{
   char MyStr[SIZE];

   printf("Enter your word: ");
   scanf("%19s", MyStr);
}

This picture is from the Sixth Edition online:

enter image description here

But when I do:

int main()
{
   char MyStr[20];

   printf("Enter your word: ");
   scanf_s("%19s", MyStr);
}

I get Access Violation error:

enter image description here

What is that I am doing wrong?

7
  • I recommend that you read the documentation for scanf_s. It's a special function that requires special extra arguments in some cases. Commented Nov 1, 2018 at 12:35
  • 1
    "scanf_s requires the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable." Commented Nov 1, 2018 at 12:45
  • 2
    You've fallen into the trap of Microsoft telling you to use scanf_s and lies about scanf not being "safe" and whatnot - there is no change in safety here between scanf and scanf_s given the format from the book. Commented Nov 1, 2018 at 12:46
  • @Someprogrammerdude That's not the documentation for scanf_s. It is found in Annex K of the standard, the "bounds checking interface". Commented Nov 1, 2018 at 12:50
  • @Lundin Unfortunately Visual Studio have their own variants of the "safe" functions, that are similar but not the same as the standard functions of the same name (at least they used to be a little different). Commented Nov 1, 2018 at 12:51

2 Answers 2

3

There is a difference between scanf and scanf_s. The latter requires the length to be specified. So your code should be changed to:

int main()
{
   char MyStr[20];

   printf("Enter your word: ");
   scanf_s("%19s", MyStr, sizeof(MyStr));
}

or

int main()
{
    char MyStr[20];

    printf("Enter your word: ");
    scanf("%19s", MyStr);
}
Sign up to request clarification or add additional context in comments.

3 Comments

My IDE is not allowing me to use scaf(), so I added the size parameter to scanf_s() and it worked.
@Lundin Yeah and make the solution even more complex by finding a better book
@SandraK Learning bad, non-standard practices with an outdated compiler isn't going to make you a decent C programmer. Visual Studio is at best to be regarded as a C++ compiler.
0

Add _CRT_SECURE_NO_WARNINGS to linker options and it should allow you to use scanf and other "unsecure" methods if you don't want to use safe ones. Visual Studio by default prefers if you use secure ones

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.