Why use pointers as function parameters?

Asked

Viewed 476 times

5

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

Currently I have been studying algorithms through the portal Geeksforgeeks, I thought he was really cool because he has the codes as an example. Now I don’t understand why every parameter of a function the variables are treated as pointers and arrays also.

Example:
http://www.geeksforgeeks.org/c-program-swap-two-numbers/

  • I tried to improve your question, I hope you don’t mind

  • It’s much better. Thank you.

1 answer

9


Good materials explain why instead of setting an example.

Data is passed to functions by value, so there is a copy of its value from argument for the parameter. This can be desired or not. When not desired the pointer serves as indirect to avoid copying the data. 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 big. 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 the execution of the function finishes everything that was changed in that object must be preserved in the original object passed to it. How is passing the address where the object is, anywhere is referencing the same object, touched it, all places that see it come to see this change since it is not a copy. Copies produce a new independent object.

This is an important semantic change in how value is treated.

Arrays are pointers?

  • Thank you very much colleague, it was very clear now... As I also learned some new things. Thank you !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.