Main Content

Just pass a pointer - do not duplicate the data

Archive - Originally posted on "The Horse's Mouth" - 2010-06-30 06:29:10 - Graham Ellis

When you want to pass a big bundle of data - such as an array - into a function, it's far more efficient to pass in just a single value in the form of a pointer to the array. That's the address in memory at which the array starts and that single value can provide the key to all the data without havig to duplicate it. By passing in the address rather than a copy of the data, it also means that the C function can - if it wishes - modify the original copy of the data and not just a duplicate which would be lost when the operation of the function completes.

From yesterday's C Course, I've added an example of passing in the address of the start of an array to a function to our source examples - see [here]. The parameter is passed in as
  &stuff[0]
and picked up by the declaration
  int * options

You'll want to do this so often that you can use a shorthand - if you just pass in the array, it automatically assumes that you mean the address of the first element, and you can also collect the parameter using array notation:
  int options[]
See source code [here].

If you don't know at compile time how big you need your array to be, you can allocate memory to be used as an array with a function such as calloc; the resultant memory does not have its own variable name, so it has to be accessed only via pointers. I've extended the above examples into an equivalent using calloc - source code [here]. There are further examples in the memory management module too - see [here].




This is really a "C" example ... but a similar principle applies in Perl. If you pass in @abc to a sub, then you're duplicating the data. If you pass in \@abc then you're passing in a reference - that's in effect a sophisticated pointer.