Why use pointers as function parameters?

3

I already have some knowledge about pointer, but I wanted to understand why in most cases people use pointers as parameters in functions.

I'm currently studying algorithms through the GeeksforGeeks portal, which I find very cool because it has the codes as an example. Now I do not understand why every parameter of a function variables are treated as pointers and arrays as well.

Example:
link

    
asked by anonymous 18.05.2017 / 13:46

1 answer

7

Good materials explain why, rather than playing the role of example for the person to turn around.

Data is passed to functions by value, so there is a copy of your argument to parameter . This may be the desired or not. When not desired the pointer serves as indirection to avoid copying the data. In this way what will be copied is only the pointer and not the value that matters. This has two advantages.

Avoiding copying is an obvious advantage when the data is too large. Copying 4 or 8 bytes is much faster than copying tens, hundreds, thousands, or millions of bytes.

Another reason is when you need the change made in the parameter to be reflected in the argument variable, that is, when you finish executing the function everything that was changed in that object must be preserved in the original object passed to it. As it is passing the address where the object is, anywhere is referencing the same object, moved it, all places that see it happen to see this change since it is not a copy. Copies produce a new, independent object.

This is an important semantic change of how the value is treated.

Arrays are pointers?

    
18.05.2017 / 14:00