C - Exception thrown to scanf_s ler string

Asked

Viewed 269 times

-1

I’m doing a lot of my college activities that should be done using C, I’m struggling because I’m used to using only C++, I was first using scanf but the visual studio did not compile indicating security errors, so I migrated to scanf_s, compiled, but when reading a string I get the following error:

inserir a descrição da imagem aqui

Here’s the code:

struct Conta {
    char *nome;
    int numeroConta;
    int kwConsumidos;
};

struct Conta conta;

printf("Insira o nome: \n");
scanf_s("%s", &conta.nome);
  • A piece of advice. In visual studio, when programming in C, prefer to use the compiler Clang (can be downloaded by the visual installer) than MVSC (the natural compiler of visual studio) because visual studio, for C, has a serious compatibility problem with the ISO standard rules. These module functions <stdio. h> ending in _s are not recognized by other compilers, so the code is not portable, in addition, MVSC does not have support for _Generic, makes confusion with noreturn, has no VLA..., in short, it is quite problematic to program C with it.

  • @v.Santos I like to use llvm in my projects, but who will correct the activity will not want to do this

1 answer

1

Ask the teacher to explain again about pointers.

The member 'name' of the 'account' structure is a pointer, it needs to be allocated, to have space that receives the string inserted.

Also, because of the &, you are passing a pointer to the pointer, type char**, but scanf/scanf_s asks for the type char* for the %s mask.

  • but how will I allocate memory to pointer if I don’t know the size the user will insert?

  • It is, this is a fundamental limitation of scanf() & cia. You will need to set a maximum size and allocate. The function scanf_s() allows passing a third parameter of this size, so at least the program will not explode if the input exceeds it.

  • Passing the size to the function made it work

  • Yeah, it’s better to specify, but if you don’t allocate space to Account.name and keep sending char** instead of char*, you’re writing the string somewhere mysterious, stopped breaking by luck.

  • I changed pointer to array and passed array size with parameter

Browser other questions tagged

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