[CSI] Passing Pointers as Arguements

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Aug 5 23:04:10 EDT 2021


> I have one more question that is related to yesterday's lecture. I
> was watching the lecture recording and in the printArray function,
> when we changed the 4th element of the array. It affected the memory
> location that p pointed to. So when you pass a pointer are they
> always passed by reference like arrays?

Pointers, like regular variables may be passed either by value or by
reference. The usual semantics of pass-by-reference and pass-by-value
applies.

The difficulty is that a pointer just hold an address of another
variable. Therefore, even if a pointer is passed by value,
dereferencing it and modifying this value, would be visible to the
argument pointer.

For example



void myfunc(int*); // accepts a pointer by value

int main(){

    int *p;
    p = new int(55);

    myfunc(p);  // passes "p" by value

    cout << *p; // prints out 66

}



void myfunc(int *x){  
       // "x" and "p" are two different pointers
       // but they point to the same memory location

       *x = 66; // modifies the value pointed to by both "x" and "p"
}




Thanks,
--
Mikhail


More information about the cs13001 mailing list