1

There is a function, which I wish to add numbers to each element in arrays, with only pointers. But I'm failing it. The main problem is what to do with adding the sum. The pointer results in errors in the while loop.

void f(int *a, const int len) {

  const int *pointer = a;
  const int *add;


  while (pointer < a + len) {
    (a + pointer) += add; //this is like a[p], but with pointers, it's not working

    ++ pointer;
  }

}
2
  • Pointers can be subtracted, but I'm not sure if they can be added. Let me jusrt check to confirm that. Commented Feb 25, 2021 at 6:47
  • Yes, I was correct. see this question. Commented Feb 25, 2021 at 6:47

1 Answer 1

4

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
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I always try and comment after a while (len--) { that it will /* loop len times */ as it may not be immediately apparent to new C users (though they should be able to deduce as much)
@DavidC.Rankin Good point, I added a couple of comments.
This is a good candidate for the downto operator: while (len --> 0) { *ptr++ += 101; }
Oh that is almost cruel :)
@chqrlie Ah, of course. The downto operator is one of those core language features one learns on SO, right next to C++ analog literals ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.