Friday, July 29, 2016

C Basics - Pointers and Functions in C

Passing Pointers to functions in C:
Pointers can be used in function parameters. To do so, simply declare the function parameter as a pointer type.

return_type myfunction(type *paratemer1) {
statement(s);
}

Example:

#include 
int sum(int *ptr, int size) {

   int i;
   int sum = 0;

   for (i = 0; i < size; ++i) {
      sum += *ptr;
   ptr++;
   }   

   return sum;
}
int main () {

   int balance[5] = {1000, 2, 3, 17, 50};
   int total;
   int *ptr = NULL;

   /* pass the array as an argument */
   total = sum( balance, 5 ) ;
 
   /* output the returned value */
   printf( "Sum1 value is: %d\n ", total );
   
   /* pass pointer to the array as an argument */
   ptr = balance;
   total = sum( ptr, 5 ) ;
 
   /* output the returned value */
   printf( "Sum2 value is: %d ", total );
    
   return 0;
}
Output of above program,

Sum1 value is: 1072
 Sum2 value is: 1072

Return Pointer from Function in C – Function Pointer:
Function can return pointers. To do so, simply declare the function return type as a pointer .

return_type *myfunction(type paratemer1) {
statement(s);
}

The function return value is a pointer that points to an return_type.

It is not a good idea to return the address of a local variable outside the function, so you have to define the local variable as static variable.

#include <stdio.h>
#include <stdlib.h>

int *sum(int *ptr, int size) {

   int i;
   static int sum;
   int *sumptr = ∑
   *sumptr = 0;

   for (i = 0; i < size; ++i) {
      *sumptr += *ptr;
   ptr++;
   }   

   
   return sumptr;
}
int main () {

   int balance[5] = {1000, 2, 3, 17, 50};
   int *total = malloc(sizeof(int));   

   /* pass the array as an argument */
   total = sum( balance, 5 ) ;
 
   /* output the returned value */
   printf( "Sum value is: %d\n ", *total );   
    
   return 0;
}
The output of the above program would be:

Sum value is: 1072

Pointer to a function:

int (*f)() 

This is a pointer to a function. The name of the pointer is 'f'. But the function it points to could be any function that takes no parameters and returns an int.

They are common is in API functions that take a call-back function (i.e. a function that's going to do some body of work, and a part of that work is going to include calling a function that you specify). They can also be used as a part of lookup tables.



Related topics:
Pointers in C   |   Pointer Arithmetic in C   |   Pointer to an Array in C   |   Returning Array from a Function in C   |   Array of Pointers in C   |   Pointer to Pointer in C

List of topics: C Programming

No comments:

Post a Comment