in Programming in C edited by
535 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?
in Programming in C edited by
535 views

1 Answer

4 votes
4 votes
Best answer
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

2 Comments

@amuchand @hemant

 

1.When p is assigned a string "%d\n" it says format an integer to print its value and then print the carriage return character

What you mean by this?..Not able to understand

2. 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.

Please explain above 2 points..I'm not able to understand
0
0
@amuchand.....that means we can put pointer at the place of format string
0
0