0

I have absolutely no clue, what the difference is between the two following examples:

void function(int *p) {

p++;

}

int main() {

int values[] = {1,2,3};
int *p = values;
function(p);

cout << *p;

return 0;
}

This one returns "1".

Whereas a slight modification yields "2" (which is the wanted result):

int main() {

int values[] = {1,2,3};
int *p = values;
p++;

cout << *p;

return 0;
}

Where lies the problem? Is it due to passing by reference or incrementing?

2
  • 1
    To see what's going on more clearly, change void function(int *p) { to void function(int *argument) {. When you do argument++, the p variable in the caller is not affected at all. Commented Aug 5, 2016 at 12:43
  • c++ is always pass-by-value. To get pass-by-reference you have to pass a reference (eg a pointer) by value. In your case you would need either a reference or pointer to that pointer to change it inside the function. Commented Aug 5, 2016 at 12:48

3 Answers 3

4

The issue here is

void function(int *p) {
    p++;
}

Is using pass by value - not pass by reference. Since the pointer is passed by value any change you make to the pointer itself is not reflected in the call site. If you need to modify where the pointer points then you need to pass it by reference like

void function(int*& p) {
    p++;
}

Now when you increment it will point to the second element like it does in your second example.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for showing me an alternative approach. I have never seen it done like this and we weren't taught.
No problem. Glad to help.
2

In this example

void function(int *p) {

p++;

}

int main() {

int values[] = {1,2,3};
int *p = values;
function(p);

cout << *p;

return 0;
}

You are passing a pointer by value, which means you simply pass a copy of the address the pointer is pointing at. You then proceed to increment the function's local copy of that pointer and then exit the function. This has no effect on the original pointer as you incremented a local copy.

In this example, however

int main() {

int values[] = {1,2,3};
int *p = values;
p++;

cout << *p;

return 0;
}

You directly increment your pointer, which means it is now pointing at the next element in the array.

Comments

0

In the first case the value of address is passed by value.

function(p) ==> void function(int *p){}

The 'p' on right side a local variable. So any modification to the pointer will be visible only inside function.

Comments

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.