23 Functions with Arrays and Pointers

Ordinary variables are passed as arguments to functions using a copy of the values that the variables contain. The result of this “pass by value” approach is

  • a function can modify a value passed as an argument without having any effect on the contents of the original variable. This keeps functions from breaking the code that calls them and is a good thing.
  • the code calling the function has no feedback from the function, except through the value returned from the function. This can be difficult if you wanted to get multiple pieces of information back from a function, maybe like a mean and a standard deviation.

Arrays are Passed by Reference

When you use an array as an argument in C, the function receives a reference to the memory location where the array is stored, not a copy of the entire array. This is memory and time efficient, and allows the calling code to see any changes that are made in the array by the function. This video (2:25) shows how to pass arrays and get the contents back from a function.

Pointers as Arguments

For single valued variables, you can still pass a reference to their location in memory, allowing the function to change the value in the underlying variable. This is done with the * and & operators. *a is the thing pointed to by the address contained in variable a, while &b is a pointer to the memory location of variable b. It’s probably clearer if you see them in use as in this video (6:35)

It can often be useful to keep a history array with more than just a couple of recent measured values and pass these arrays to functions for processing.

 

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Rick's Measurement for Mechatronics Notes Copyright © 2019 by Rick Sellens is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book