Im trying to read from stdin something like abc.com but a[0]=’\0′ after run scanf instead of ‘a’. Im using %[^.] to read all character until find a ‘.’.
#include <stdio.h>
int main() {
char a[6];
char b[4];
int i = scanf("%[^.]%s", a, b);
printf("%d\n", i);
printf("a: %s\n", a);
printf("b: %s\n", b);
printf("%c\n", a[0]);
printf("%c\n", a[1]);
printf("%c\n", a[2]);
if (a[3]=='\0') puts("why?");
return 0;
}
>Solution :
Trying char b[5]; will get you an output of
2
a: abc
b: .com
a
b
c
It indicates that you have read 5 characters into b, the fifth being the '\0' which overwrites a[0]. The first one being the '.', which intentionally is the NOT read by the format for a. You hence write beyond b (which is undefined behaviour and I should stop explaining right now….).
One of the possible behaviours of this UB is that the fifth read character for b is written beyond and into the first entry of a.