The following is the original code with the minimal corrections to make it work, and some comments to explain the changes:
void f(int *a, const int len) {
const int add = 101; // must initialize `add` here, since it's `const` and can't be modified later
int *pointer = a; // initialize `pointer` to point to the first element in the array
// can not be `const int *` since `*pointer` must be writeable
while (pointer < a + len) {
*pointer += add; // add `add` to the current element that `pointer` points to
++pointer; // increment `pointer` to point to the next element
}
}
Looking at the while
loop, it gets executed len
times if len > 0
, or not at all if len <= 0
. Then the whole function can be rewritten in a more idiomatic C way as follows:
void f(int *ptr, int len) {
const int add = 101;
while (len-- > 0) { // loop 'len' times
*ptr++ += add; // equivalent to `*ptr += add; ptr++;` due to operators precedence
}
}