Variable char error C Visual Studio

Asked

Viewed 108 times

2

I’m having problems using scanf_s in a char variable only in the visual studio. When it reaches the scanf_s line the program stops and brings me the following error:

Exception thrown at 0x7893E63C (ucrtbased.dll) in exercicio4.exe: 0xC0000005: Access Violation writing Location 0x00F00000.

This only happens in Visual studio, when using compilers online does not occur

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char a[25];

    printf("Digite seu primeiro nome: ");
    scanf_s("%s", a);


    return 0;
}
  • Try to run as an administrator.

1 answer

1


The function scanf_s has an optional third parameter, which represents the size of the buffer in characters. I believe this is the problem that occurs in your case (not specifying this parameter), since the problem is "write access violation".

Quoting documentation:

The size of the character buffer is passed as a parameter additional. It immediately follows the pointer to the buffer or the variable. For example, if you are reading a string, the buffer size of this string will be passed from next way:

char s[10];
scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification    

In your case, try:

scanf_s("%s", a, (unsigned)_countof(a));

or

scanf_s("%24s", a, (unsigned)_countof(a));

  • really the first solution given solved my problem thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.