I have a program where I need to scanf a string, which I know it will be only 2 characters long. (for example: \"ex\"). what is the proper way to do that?
I was goin
but when I enter a 10-letter word it also works just fine. How come? Does the [3] has no meaning?
I doesn't work fine. See in this example:
#include
int
main(int argc, char **argv)
{
char second[5] = "BBBB";
char myStr[3] = {0};
scanf("%s", myStr);
printf("second = %s\n", second);
printf("myStr = %s\n", myStr);
return 0;
}
writing only two characters in myStr
is fine:
a.exe
AA
second = BBBB
myStr = AA
writing more data overrides the near by memory of second
:
a.exe
AAAAAAA
second = AAAA
myStr = AAAAAAA
You need to limit the number of characters scanf
reads using something like
scanf("%2s", myStr);
, 2
is the size of myStr - 1
.