You can test on your own:
#include <stdio.h>
int main(void) {
char nomeSobrenome[40];
printf("Insira seu nome e seu sobrenome:\n");
scanf("%[A-Z a-z 0-9 !-_]s", nomeSobrenome);
printf("%s\n", nomeSobrenome);
for (int i = 0; i < 40; i++) printf("%c = %d, ", nomeSobrenome[i], nomeSobrenome[i]);
}
scanf()
always delivers a complete string , which obviously includes the terminator.
It does not matter how much the formatting is applied, this aspect being asked does not change. What will change is how to interpret the input data or how to manipulate the buffer , but the end result is always the same under normal conditions. This function guarantees a well formed string or gives an error (usually the correct one is to check if everything happened well before using the data).
If you use scanf("%s", nomeSobrenome);
it would give the same to the terminator.
In C there is no string , it only works with an array of char
and this does not include its size, design that we have to live with. The only way to identify the end of string in C is to find the terminator, so any supposed string that does not have a terminator is an error.
scanf()
can corrupt memory if it does not have a specific limit; in its example it should be 39 ( scanf("%39s", nomeSobrenome);
). If someone types more than this, they may have problems.
If you read more different data, each data will go to a variable and will be formed with the terminator.
What I did in the above code was to print all 40 bytes that you reserved in the sobreNome
variable. I have to print as a character ( %c
) and then as number to be more obvious ( %d
). What comes after the terminator can come anything that was already in memory before.
If you used printf()
with %s
which is the default for string or another function that considers the terminator would stop the loop as soon as it finds %code%
, which is correct under conditions normal.
To visualize better and not pick up memory garbage I will now initialize the variable:
#include <stdio.h>
int main(void) {
char nomeSobrenome[40] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
printf("Insira seu nome e seu sobrenome:\n");
scanf("%[A-Z a-z 0-9 !-_]s", nomeSobrenome);
printf("%s\n", nomeSobrenome);
for (int i = 0; i < 40; i++) printf("%c = %d\n", nomeSobrenome[i], nomeSobrenome[i]);
}
See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .