C Programming - Pointers - Discussion

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

int main()
{
    char *str;
    str = "%d\n";
    str++;
    str++;
    printf(str-2, 300);
    return 0;
}
No output
30
3
300
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
43 comments Page 3 of 5.

Rishu said:   8 years ago
I think its wrong because we can't increment a string constant pointer.

Aditya Pandey said:   8 years ago
Let adress of str =5000.
When it increased twice = 500+(1*4)+1*4)=5008.
But in the next line, there is str-2, it comes back on it's previous location.
So it prints value 300.

HarshaN said:   1 decade ago
@Vallabh

Why only one argument in the printf gets printed instead of two arguments in your second example?

Some one pls explain

Archana said:   2 decades ago
Twice str is incremented n then when we do str-2, it is again pointing to starting position. So str contains "%d\n".

So printf statement would be like printf("%d\n",300);

Hence output will be 300.

Sunitha said:   1 decade ago
Thank you very much archana.

Sohan lal mits said:   1 decade ago
We know that when we increament pointer wihh n values like then pointer point to nth value address and whereas pointer decrease with nth value so pointer locate same address as previus so according question
char *str;
str = "%d\n";
str++;
str++;
printf(str-2, 300);
output:300

Suresh said:   1 decade ago
Thank you sohan lal mits. There is clearance in your explanation. Thanks a lot.

Pavan said:   1 decade ago
Thank you sohan and archana.

Sujith said:   1 decade ago
str-2 one's incremented then it becomes str-1
then again incremented then it becomes str
then str="%d\n"; then 300 will print

Jasmin said:   1 decade ago
Can any body explain what happened to printf (str-2, 300) why only 300 is answer ? Why the value of str-2 is not printed. ?


Post your comments here:

Your comments will be displayed after verification.