Last active
September 14, 2017 22:36
-
-
Save elliott-beach/f73ab2d0e82966e7e878bcbff86f63a1 to your computer and use it in GitHub Desktop.
Problem 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Here’s a function that’s intended to reverse the order of a subsequence of integers within an | |
array. For instance suppose the array a originally contains the integers 1 2 3 4 5 6 7 8 9. If | |
you call reverse_range(a, 2, 5), the afterwards the array a will contain the same integers but | |
with the ones in positions 2 through 5 (counting from zero) in the opposite order. I.e., a will be 1 | |
2 6 5 4 3 7 8 9. | |
Unfortunately you’ll see that this function was not implemented very carefully. | |
*/ | |
/* | |
Describe at least three bad things that could happen when running this function in situations | |
that the programmer probably didn’t think of. For each case, identify the programming | |
mistake, the problematic situation, and the bad outcome. | |
*/ | |
/* Reverse the elements from FROM to TO, inclusive */ | |
void reverse_range(int *a, int from, int to) { | |
int *p = &a[from]; | |
int *q = &a[to]; | |
/* Until the pointers move past each other: */ | |
while (!(p == q + 1 || p == q + 2)) { | |
/* Swap *p with *q, without using a temporary variable */ | |
*p += *q; /* *p == P + Q */ | |
*q = *p - *q; /* *q == P + Q - Q = P */ | |
*p = *p - *q; /* *p == P + Q - P = Q */ | |
/* Advance pointers towards each other */ | |
p++; | |
q--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problems include:
Also,
from
orto
could be negative, but I feel like we should let the programmer do that if they want to?