简体   繁体   中英

Having trouble regarding output of a printf statement

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.

2 - 2 is equal to 0 .:)

In fact these two expression statements

str++;
str++;

that can be rewritten like

str = str + 1;
str = str + 1;

are equivalent to one statement

str = str + 2;

Then in the statement with printf

printf(str-2, 300);

you are using the expression str-2 that points to the first character of the string literal "%d\\n" Or the value of the expression str-2 is equal to the original value of str .

(Do you remember that 2 - 2 == 0 ?)

So the statement above is equivalent to

printf(str, 300);

when str was initially initialized by the string literal "%d\\n"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM