Array as function parameter, the pointer increment does not count for callee

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
void plusOne(int* array) {
  array++;
  std::cout << *(array) << std::endl;
}
int main(int argc, char *argv[]) {
  int array[6] = {0, 1, 2, 3, 4, 5};
  plusOne(array);  // prints 1
  plusOne(array + 1);  // prints 2
  plusOne(array + 2);  // prints 3
  std::cout << *(array) << std::endl;  // prints 0
}


I just go with the example above to my question.
In the function plusOne the pointer is incremented.
But this increment step doesn't count when the plusOne function is ended.

But what I want is such things. How can I achieve that?
1
2
3
  plusOne(array);  // prints 1, and array points at array[1] because of the ++
  plusOne(array + 1);  // prints 3, and array points at array[3] because of the ++
  plusOne(array + 2);  // out of bound 
Last edited on
You're currently passing array by value. That means that any change to array within plusOne won't affect the value. If you want to change the value of the parameter that was passed in, then you could change plusOne to use a reference:
void plusOne(int * &array) {...

But if you make this change, then plusOne(array+1) and plusOne(array+2) won't compile. That makes sense if you think about it. What does it mean to increment array+1 in the calling program?
> What does it mean to increment array+1 in the calling program?

I mean not so much here, just to indicate my problem and distinguish the different positions.

Thanks!
Topic archived. No new replies allowed.