Modification of a variable by a function requires that it be passed by
reference
Remember that when we wanted to modify an integer variable, we passed the
address of that variable into a function and the type of the function's
parameter that accepts it is int*, or a pointer to an int.
Similarly if we want to modify a variable which is a pointer to an int, we will pass the address of the variable into the function and the type of the function's parameter that accepts it will be int**, or a pointer to a pointer to int.
/*********************************
** File malloc2.c
** Author: S. Bogar
** Date: 1/3/95
** Modified: 9/26/05
** Section: 101
** E-Mail: bogar@cs.umbc.edu
**
** This file demonstrates passing a pointer
** by reference to a function
** A pointer to a pointer
*******************************/
#include <stdio.h>
#include <stdlib.h>
/* function prototype */
void GetMemory (int count, int **arrayPtr);
int main()
{
int i, *values, nrElements ;
int powerOf2 ;
printf("Enter number of elements in integer values: ") ;
scanf("%d", &nrElements) ;
/* get a block of memory for 'nrElements' integers
** since 'values' is a pointer to int
** '&values' is the address of (pointer to) a pointer
** to int so that 'values' can be modified in the
** function
*/
GetMemory (nrElements, &values);
/* Lets use the memory as an arrray */
powerOf2 = 1 ;
for (i = 0; i < nrElements; i++)
{
values[i] = powerOf2 ;
powerOf2 = 2 * powerOf2 ;
}
/* Print out contents of the array */
for (i = 0; i < nrElements; i++)
{
printf("values[%d] = %d\n", i, values[i]) ;
}
/* Give up use of the memory block */
free(values) ;
return 0;
}
/***************
** Function: GetMemory
**
** GetMemory() gets the memory space needed and modifies the pointer
** that will point to it in the calling function using call by reference
**
** Inputs: Number of integers for which to allocate
** space
** Pointer to the pointer that will point to
** the memory
** Output: The pointer to the memory is set by this function
** there is no return value
********************************/
void GetMemory (int count, int **arrayPtr)
{
/* malloc the memory and set the caller's pointer
** to point to it
*/
*arrayPtr = (int *) malloc( count * sizeof(int) ) ;
if (*arrayPtr == NULL)
{
printf("Oops, we're out of memory\n") ;
exit(-1);
}
}