Passing Pointers to Functions

A pointer can be passed into a function by using the ampersand & address of operator for the variable, as the parameter in the function call.

 

The receiving function accepts the parameter as a pointer of the same data type, which is then used within the function as per normal pointer operation:

#include <stdio.h>
#include <time.h>

void getSecs(int *par)	//function argument being passed in as a pointer
{
   *par = time(NULL);	//pointer is assigned the current time (in seconds)
   return;
}

int main ()
{
   int sec;	//declare an int
   getSecs( &sec );	//call getSecs passing address of sec into function

   printf("Number of seconds: %d \n", sec );

   return 0;
}

Compile & Run:

Number of seconds: 1360667276

Leave a Reply