C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - Find Output of Program (Q.No. 8)
8.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char *p;
    p="%d\n";
    p++;
    p++;
    printf(p-2, 23);
    return 0;
}
21
23
Error
No output
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
25 comments Page 1 of 3.

Rohit Bachhav said:   2 years ago
@All.

Here is my coding part. Please refer it.

p++ goes to 'd'
2nd p++ goes to '\'
and p-2 goes to '% ' at the starting of the pointer

So,
printf becomes printf("%d\n",23)
it treats %d= format specifier
and \n = newline character
So that's why it prints 23 (int).
(3)

Ashu said:   6 years ago
As far as I know, it's just based on pointers concept. Here "p" is a pointer which points to an address.

An address will be stored in the variable p. Let us assume that address to be 1000. in the above program. The value "%d\n" is assigned to "p" which means that value is stored in the address 1000.. when we give p++ twice.

The value stored in "p" will get incremented twice which means p++=1000+1=1001, again p++=1001+1=1002. So the current value(address) stored in p=1002.."p" is now pointing to the address 1002.

But the value which we assigned "%d\n" is stored in the address 1000 inorder to make p point to that address(1000) we give p-2, where p=1002-2=1000.

Now, p will again point to 1000 so the printf(p-2,23); should be seen like this printf("%d\n",23);. Hence it prints the value 23.
(4)

Hritik singh said:   7 years ago
Can anyone explain me what exactly happening inside printf statement's braces? Please.

Basha said:   8 years ago
Please explain me clearly.

Arihant said:   8 years ago
Nice @Priyanka.

Vishalakshi said:   9 years ago
Thank you @Abhinav Singh.

Nidipa said:   9 years ago
Please can any one explain clearly? I didn't understand this program.

Ravi rathore said:   9 years ago
Nice explanation @Priyanka.

SALAMUDDIN said:   9 years ago
You're absolutely right @Priyanka.

Vishal said:   10 years ago
What about the char type man? How can it change from character to integer?


Post your comments here:

Your comments will be displayed after verification.