سؤال

This code causes a segmentation fault when running. It's due to the odd pointer incrementation, but I don't understand why this is a problem, as it seems to make sense.

I think it should: increment the pointer, then dereference the unincremented pointer, then increment the value 10 to 11. So out = 11, and the first value in the array is now 11. So this loop should print out 11, 21, 31, 1, then go on infinitely printing out values outside the array. This is clearly bad practice but we just want to see why this double pointer incrementation isn't valid.

My code:

int main() {
     int myarray[4] = {10,20,30,0};
     int *p = myarray;
     int out = 0;
     while (out = ++(*p++)) {
         printf("%d ", out);
     }
 }          
هل كانت مفيدة؟

المحلول

The while loop never terminates:

First iteration:

*p = 10, out = 11

Next iteration:

*p = 20, out = 21

Next iteration:

*p = 30, out = 31

Next iteration:

*p = 0, out = 1

Next iteration:

You are accessing unauthorized memory, which leads to undefined behavior.

Update

After the last item from the array is accessed, the part of the stack frame that contains code gets trampled over by the increment operator. Hence, the code cannot be expected to behave in a logical manner.

نصائح أخرى

Here:

while (out = ++(*p++))

The preincrement (the first "++") returns the incremented value. So when you reach the end of the array, it returns 1, which evaluates to true, and the loop keeps going.

When p exceeds the range of myarray, deference causes undefined behavior.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top