C Programming Tutorial
About Lesson

C Pointers & Functions

In this tutorial, we will learn to pass memory addresses and pointers as arguments to functions with the help of some examples.

To learn about Pointers and Functions click on the given links.


Passing memory addresses to function using pointers

In C programming, we can pass memory addresses to functions as arguments with the help of pointers.

Example: Pass Memory Addresses to Function

#include <stdio.h>
int totalSalary(int *expend_pointer, int *sav_pointer) {
  return *expend_pointer + *sav_pointer;
}

int main() {
  int expenditure, saving, salary;
  printf("Enter your expenditure per month : ");
  scanf("%d", &expenditure);
  printf("Enter your savings per month : ");
  scanf("%d", &saving);
  salary = totalSalary( &expenditure, &saving);
  printf("Total earning : %d", salary);
  return 0;
}

Output :

Enter your expenditure per month : 1200
Enter your savings per month : 1500
Total earning : 2700

 

In the above example, we have declared two variables expenditure and saving of int type to store user input and pass their memory addresses to function totalSalary.
Then, we add their stored values using their memory addresses.

Note : To accept memory addresses in the function definition, we can use pointers because pointers are used to store addresses.


Example : Pass Memory Addresses to Function

#include <stdio.h>
int swapNumber(int *num1, int *num2) {
int swapper;
swapper = *num1;
*num1 = *num2;
*num2 = swapper;
}

int main() {
  int firstNum, secondNum;
  printf("Enter first number : ");
  scanf("%d", &firstNum);
  printf("Enter second number : ");
  scanf("%d", &secondNum);
  swapNumber( &firstNum, &secondNum);
  printf("First Number : %d\nSecond Number : %d", firstNum, secondNum);
  return 0;
}

Output :

Enter first number : 12
Enter second number : 34
First Number : 34
Second Number : 12

In the above example, we have declared two variables firstNum and secondNum of int type to store user input and pass their memory addresses to function totalSalary.
Then, we have use their memory address to swap their values using a variable swapper of int type.

error: Content is protected !!