Nic Nic - 4 months ago 10
C++ Question

Moving a pointer through array - passing by reference or incrementation?

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?

Answer

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.