Explanation of output of this C code

Please post your actual code, not what you intended to type. Actually copy-paste your real code.

Because you typed it in wrong.

You either put extra {} in here:

while(i++ < n) {
    p = &arr[i];
    *p = 0;
}

or you used a comma instead of a semicolon:

while(i++ < n)
    p = &arr[i],
*p = 0;

and so the assignment to zero ran every time.

Edit to add: Yep, you put extra {} which the original question didn’t have. So in your code, the “*p = 0” executes every time round the while loop, whereas the original question the “*p = 0” only executes once and clobbers some random data that is one past the end of the array.

(By the way, the answer to the original question is actually “it is undefined behaviour; the program doesn’t necessarily print anything. Valid behaviours include printing 1 2 3 4, printing 42 42 42 42, crashing, and formatting your hard drive.”)

Browse More Popular Posts

Leave a Comment