C Tutorial C References

C - Passing Pointer to Function



In C, a function can accept pointer as argument and when a pointer is passed as argument in the function, then the function takes the address of that parameter and any operation performed on the passed parameter is performed at its memory location inside the function. This means that any changes made to the parameter inside the function will change the parameter itself also.

Example:

In the example below, the function called Square is created which takes a argument as pointer and returns the square of it. It takes the address of the parameter and modify the parameter to the square of itself at its memory location. Therefore, when the passed argument is printed after calling the function, its value gets changed.

#include <stdio.h>

int Square(int *x){
  *x = (*x)*(*x);
  return *x; 
}

int main (){
  int x = 5;

  printf("Value of x: %i\n", x); 
  printf("Function returns: %i\n", Square(&x)); 
  printf("Value of x: %i\n", x); 
  return 0;
}

The output of the above code will be:

Value of x: 5
Function returns: 25
Value of x: 25

Example:

A function which accepts pointer as an argument and can also accept an array. Consider the example below:

#include <stdio.h>
int ArrayAverage(int *arr, int n); 

int main (){
  int Arr[5] = {10, 20, 30, 40, 50};

  printf("Average of all elements of Arr = %i\n",
         ArrayAverage(Arr, 5)); 
  return 0;
}

int ArrayAverage(int *arr, int n){
  int sum = 0;
  for(int i = 0; i<n; i++) {
    sum = sum + arr[i];
  }
  return sum/n; 
}

The output of the above code will be:

Average of all elements of Arr = 30

❮ C - Pointers