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 4 of 5.

Yashwanth P said:   10 years ago
@Nejat.

It's just an assumption. The memory location is allocated randomly by the CPU. It can be any number.

Amol said:   9 years ago
Nice explanation.

Siya said:   9 years ago
Can we declare print statement like printf(str-2, 300);?

MY question is where is "%c" or " "%s"in printf statement. If it is true then how it works?
(1)

Shubham said:   9 years ago
At the starting str will points to the first character of the string which is %.

After executing two times increment operator on str pointer will skip the first two characters of the string which is %d and points to the \.

Inside the printf statement, str-2 make str point to the starting of the string .

So, the whole string will appear in the printf statement.
printf("%d\n",300).

Therefore, the output will be 300.

Swaroopa said:   9 years ago
Thanks for your answers and explanation.
(1)

Shami said:   9 years ago
Nice @Shubham.

Rani said:   9 years ago
How we can assign are str= %d/n?

Is strcpy not necessary here?
(1)

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.

Balaji said:   8 years ago
Here, Str ++means address increment.

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


Post your comments here:

Your comments will be displayed after verification.