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;
  }

}
Roofa
  • 25
  • 5

1 Answers1

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
  }
}
dxiv
  • 16,984
  • 2
  • 27
  • 49
  • 1
    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) – David C. Rankin Feb 25 '21 at 07:29
  • @DavidC.Rankin Good point, I added a couple of comments. – dxiv Feb 25 '21 at 07:32
  • 1
    This is a good candidate for the *downto* operator: `while (len --> 0) { *ptr++ += 101; }` – chqrlie Feb 25 '21 at 07:39
  • 1
    Oh that is almost cruel `:)` – David C. Rankin Feb 25 '21 at 07:40
  • @chqrlie Ah, of course. The [*downto* operator](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c-c) is one of those core language features one learns on SO, right next to [C++ analog literals](https://stackoverflow.com/a/65260420/5538420) ;-) – dxiv Feb 25 '21 at 08:01
  • @dxiv I have another question. I want to subtract it this time. It's just a bit of different question. So I want to subtract like a[i] -= add, but using pointers – Roofa Feb 25 '21 at 21:16
  • @Roofa There is one single place in the code which performs the operation `+=`. Replace that with `-=`. – dxiv Feb 25 '21 at 22:14