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

Mehul said:   1 decade ago
@Paresh is wrong

#include<stdio.h>

int main()
{
char *p;
p="%d\n";
p++;
p++;
int i=1;
int j=3;
printf("%d\n", i,j);
return 0;
}
OUTPUT:
1

Dakshya said:   1 decade ago
But this program doesn't say that pointer is now pointing on 23.

Balu said:   1 decade ago
We must assign some address value to p, but here we are assigning a string. Can anyone explain why it won't report an error and display 23.

Priyanka said:   1 decade ago
Hey I don't understand any of your explanations. I guess you guys are complicating it.

As far as I know its 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 adress(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.

Correct me if I'm wrong.

Anubhav singh said:   1 decade ago
@Priyanka.

Your overall answer is correct but there is an error in your explanation, if 1000 is the base address to which p is pointing to i.e., "%" here then p++ will point to "d", and not to the different array, but here for the purpose we need to do p-2,

Consider this program that shows the pointer arithmetic:-

#include<stdio.h>

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

Output:- d.

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

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

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

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

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


Post your comments here:

Your comments will be displayed after verification.