I am having some trouble understanding the output of the following code snippet.
#include<stdio.h>
int main()
{
char *str;
str = "%d\n";
str++;
str++;
printf(str-2, 300);
return 0;
}
The output of the code is 300.
I understand that Until the line before the printf
statement, str
is pointing to the character-%
. What I need help with is understanding that why is the printf
function printing 300.
Right before the printf
, str
is not pointing to the %
but to the \n
.
The ++
operator increments the value of str
to point to the next character in the array. Since this is done twice, it points to the \n
. When you then pass str-2
to printf
, it creates a pointer pointing back to the %
. So printf
sees the string "%d\n"
which causes 300 to be printed as expected.