1

I'm studying pointers in C++ and here is a sample code which I found in a website :

#include <iostream>
#include <iomanip>

using namespace std;

void my_fun (int *p) {
    *p = 0;
    p++;
    *p = 4;
    p++;
    return;
}
int main ( ) {

    int a[3] = {10,20,30};
    int *p = a;
    cout << *p;
    my_fun (p);
    cout << setw(5) <<  a[0] << setw(5) << a[1] << setw(5) << a[2] << setw(5) << *p;
    return 0;
}

my expected result is : 10 0 4 30 30

but I got this : 10 0 4 30 0

would you mind please explaining what happens to the last cout ?

  • `p` still points to the first element of the array. The pointer `p` itself was not modified by `my_fun`. `my_fun` merely operated on a copy of `p` – WhiZTiM Apr 16 '17 at 19:10
  • This behaviour is consistent with every other type except references, which are specifically for the purpose of being an alias to an object. – chris Apr 16 '17 at 19:11
  • You should search for and read about the difference about passing an argument *by value* and *by reference*. – Some programmer dude Apr 16 '17 at 19:21

1 Answers1

0

p still points to a[0], since in my_fun only the local copy of the pointer is modified. If you want to increment p in my_fun you can pass a pointer to the pointer.

void my_fun (int **p) {
    **p = 0;
    (*p)++;
    **p = 4;
    (*p)++;
}

The call then would be my_fun (&p);.

jhnnslschnr
  • 404
  • 2
  • 9