edited by
538 views
0 votes
0 votes
#include<stdio.h>

int main() {
    char *p;
    p = "%d\n";
    p++;
    p++;
    printf(p-2, 400);
    return 0;
}

Output : 400

I ran this program and got 400 as output. But I don't understand why it is so?
edited by

1 Answer

Best answer
4 votes
4 votes
Printf's first parameter is a format string. The variable p is a pointer to a character array which is also how strings are represented. When p is assigned a string "%d\n" it says format an integer to print its value and then print the carriage return character. Since p is a char pointer p++ means move the pointer forward 1 character. This is done twice to move p forward 2 characters so it points to the beginning of the carriage return character. P-2 says do pointer math to give a char* 2 characters in front of where p points. This is the beginning of the %d carriage return string. This becomes the format string and the second parameter 400 replaces the %d and prints itself followed by the carriage return.
selected by

Related questions

1 votes
1 votes
0 answers
1
2 votes
2 votes
2 answers
3