C program Strings Example how come the result is 98?
#include <stdio.h>
int main()
{
char s[]="%d%d%d";
int a=9,b=8,c=5;
printf(s+2,a,b,c);
return 0;
}
C program Strings Example how come the result is 98?
#include <stdio.h>
int main()
{
char s[]="%d%d%d";
int a=9,b=8,c=5;
printf(s+2,a,b,c);
return 0;
}
On
Expression s+2 speaking in images moves pointer s (in expressions array designators are converted to pointers to their first elements) two positions to the right. So the format string in the printf statement will look like
"%d%d"
because expressiom s+2points to the third character of string "%d%d%d"
As result statement
printf(s+2,a,b,c);
will output only two first arguments a and b because the pointed substring contains only two format specifiers and you will get
98
If for example you would use expression s + 4 in the printf call you would get only
9
string + xis an operation called Pointer Arithmetic. That way you are providing reference to a mathematically calculated memory area and by semantics it is equivalent to&string[x]What actually happens behind the calculation:(&string + (x * sizeof(*string)))which is why it is a very specific notion when it is applied to pointers. That stands for Arrays as well as they decay to a pointer to the first element after all.As for your code, you have the following string:
And is passed as the format string for printf, two bytes afterwards, which explicitly provides reference to
"%d%d"Therefore this:
Is later parsed as:
printf will except two integers to read from and the 3rd one will be simply - ignored.