Note that there are some explanatory texts on larger screens.

plurals
  1. POsimple C code giving segmentation fault on gcc
    primarykey
    data
    text
    <p>I found a question somewhere ... here it is and its answer with explanation.</p> <pre><code>main() { char *p="hai friends",*p1; p1=p; while(*p!='\0') ++*p++; printf("%s %s",p,p1); } Answer: ibj!gsjfoet Explanation: ++*p++ will be parse in the given order </code></pre> <p>*p that is value at the location currently pointed by p will be taken </p> <p>++*p the retrieved value will be incremented </p> <p>when ; is encountered the location will be incremented that is p++ will be executed</p> <p>Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1 doesnot print anything.</p> <p>I found something wrong with explanation on p1.I think p1 should print "hai friends" and output of p is fine as given.</p> <p>but when I tried to run the same code on gcc compiler,its giving <strong>segmentatiion fault</strong></p> <p>here is the exact code which I tried to run ..</p> <pre><code> #include&lt;stdio.h&gt; int main() { char *p="hai friends",*p1; p1=p; while(*p !='\0') ++*p++; printf("%s %s",p,p1); return 0; } </code></pre> <p>If possible edit the title ,I could not find a suitable title which would explain the situation more clearly.</p> <p><strong>EDIT :</strong></p> <p>I tried to run the modified code as suggested by <strong>Mysticial</strong> ,But what I think output should be -</p> <pre><code>ibj!gsjfoet hai friends </code></pre> <p>because I am incrementing only p0 but p1 should be as its initial place i.e. at the starting address of string.Please if anyone could explain it where I am getting it wrong ???</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload