I am trying to use scanf (or some variant like scanf_s) to send a character array from the stdin stream into a (pre-defined) character array variable.
The error (unhanled exception) is thrown at runtime by windows as soon as the user hits enter; it is triggered as soon as scanf() is called..
I am new to working with C and just trying to get the basics down of working with variables in a more low level way, its fun but sometimes frustrating
Should I just make my own scanf function? - How would one do that?
Below is the code that isnt working, in its simplest form so easy for you to read.. (Its literally just the scanf part thats throwing an exception.. gah!)
Below the code is the error message
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[20];
printf("%s\n", string);
scanf_s("%s", &string);
system("Pause");
return 0;
}
Error is:
Exception thrown at 0x1011E63C (ucrtbased.dll) in Project.exe: 0xC0000005: Access violation writing location 0x00760000.
Unhandled exception at 0xFEFEFEFE in Project.exe: 0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003).
Few things:
printf
on the uninitialized buffer string
? That is undefined behavior.scanf_s
properly to read a string, use this: scanf_s("%19s\n", string, 20);
. The general pattern is "%s", buffer, X
where X
is the capacity of the buffer. Also, notice that it's string
, not &string
.That is, if you insist on using scanf_s
at all; fgets
is better for reading strings.
User contributions licensed under CC BY-SA 3.0