Pointers and Functions

Passing Pointers to Functions

Normally in C, function parameters are passed by value. This means that if you pass a variable as a parameter to a function, the function makes a copy of that value to operate on and it leaves the original variable alone. As we can see in this example, we pass the variable x to the function square. x is initialized to 2, and is still 2 after the function call. The value of x is copied into n and it is n that is squared and returned from the function to the variable y.



Passing Parameters By Reference

In many situations, it is desirable to let a function modify the actual variable passed to it. In order to do this, we use a pointer in the function parameter (pass by reference). In order to use a function like this, you need to pass an address or a pointer to the function when it is called. Basically, you are telling the function the address of the variable that you want it to modify.


A function with a pointer parameter, for example int foo(int *q) must be called in one of two ways:
(assume: int x, *p = &x;)
foo(&x) Pass an address to the function so the address
may be assigned to the pointer parameter: q = &x
foo(p) Pass a pointer to the function so the address
may be assigned to the pointer parameter: q = p

Example-Part 1


Example-Part 2

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.