C Programming - Pointers - Discussion

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

int main()
{
    char str[] = "peace";
    char *s = str;
    printf("%s\n", s++ +3);
    return 0;
}
peace
eace
ace
ce
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
40 comments Page 4 of 4.

UmU said:   1 decade ago
@monika you done the good work thks. :).

Cfriend said:   1 decade ago
Monika you are genius yaar.

Rajesh said:   1 decade ago
*s=base adress of str
now s is pointing to p.
since s++ is a post increment , it gets incremented 3 times , not before that . so s is pointing to c .
so it pints from "ce"

Swathi said:   1 decade ago
printf("%s\n", s++ +3); here y s++ is not incremented

Suresh Paldia said:   1 decade ago
printf("%s\n", s++ +3);
In this,
first s+3 will get executed and printed. Which means s points to c. Hence, ce gets printed.
Then, s++ executes. That makes s to point to e but will not have any effect on outputed print.

Subbu said:   1 decade ago
#include<stdio.h>

int main()
{
char str[] = "peace";
char *s = str;
s++;
printf("%s\n", s+3);
return 0;
}
if you run the above code you wold know the difference...!
in the given question s++ not gets incremented b4 printing..!

Swathi said:   1 decade ago
Thanks monika..

MONIKA said:   1 decade ago
Hello lavanya.

I don't know why you are confused about this, means I don't know about your confusion, then also I would like to give some explanation.

Since here +3 is used, you have to increment upto 3 positions but pointer will not shift to that position and you will get character 'c' then string starting from 'c' i.e. "ce" will print.

And if you are thinking about the s++ yes it will work but after getting printed the string because it is a post-increment and since it is still pointing the first character of the string i.e. 'p', hence now it reaches at 'e'.

If you will use the statement after last printf statement in program.

printf ("\n%s", s) ;.

It will print string "eace".

Hope I make you understand. Thanx.

Roshan Zameer said:   2 decades ago
Hi lavanya.

Since +3 is used you have to increment it. Then you ll reach 'ce'. So it will be printed.

Lavanya said:   2 decades ago
I need answer description for this.


Post your comments here:

Your comments will be displayed after verification.