C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 14)
What will be the output of the program ?

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

Sandesh H said:   5 years ago

This may help you.

*str ultimately is a variable like any other variable that store value, since it has * it becomes pointer variable which we used to store the address of other variables to store the address of another variable say m, we "&" symbol i.e str=&m;
but here str is declared as char and str="%d\n" means in variable str %d\n is stored instead of the address.

Since str is also a variable it will also have an address.
Let's assume str is at an address 200 ( let's assume char takes 1 bytes memory since it is char it will take 1 byte only as I think).

str++ means here address increment since str is pointer variable i.e 200+1=201.
again str++ means 201+1=202.( now str is 202)

The printf(str, 300); is same as printf("%d\n",300); as %d\n is stored in str.
but here str is now 202 as it is incremented twice, therefore, they have written str-2 in printf statement.
i.e 202-2=200 i.e str which as "%d\n".

Coderx said:   6 years ago
Here, str is a pointer variable. It points to the address of the first position. Next the str variable is incremented twice. That means the str variable now points at position 2 instead of position 0. But when we perform str-2, the str variable goes back to the position 0. At position 0 i.e. str= %d, so 300 is printed.

Shobika said:   6 years ago
How char pointer stores the "%d\n"?

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

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

Aditya Pandey said:   7 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.

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

Is strcpy not necessary here?

Shami said:   7 years ago
Nice @Shubham.

Swaroopa said:   7 years ago
Thanks for your answers and explanation.

Shubham said:   8 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.

Therefore, the output will be 300.

Post your comments here:

Your comments will be displayed after verification.