scanf("%d %d"+2, &a, &b);
printf("%d\n%d", a, b);
It accepts only a
and prints a
and 0
.
Can anyone explain why this is happening? Also, if I write +1
instead of +2
, it accepts nothing and prints 0
and 0
.
This:
scanf("%d %d"+2,&a,&b);
is the same as
scanf(" %d", &a, &b);
which is the same as
scanf("%d", &a, &b);
which means that the extra &b
argument is unnecessary.
What happens here is that "%d %d"
is a char*
. Adding two to it results into a pointer pointing two bytes ahead which means that it now points to " %d"
. The leading space is unnecessary because %d
already skips leading whitespace characters.
When you use +1
instead of +2
, the scanf
is the same as
scanf("d %d", &a, &b);
which means that it expects a d
in the input followed by an integer to be assigned to a
. Since you provide a number instead of d
in the input, the scanf
fails and returns 0. Thus, nothing is accepted and the execution reaches the printf
which prints the value of both a
and b
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.