How Pointers Are Working On Function In C Programming?

Share Your Love

In this tutorial we are going to discuss about working of pointers on function in different aspects with examples.

In C programming, it is also possible to pass addresses in function argument. So let’s take an example:

Example: Pass Addresses To Functions

#include <stdio.h>
void swap(int *n1, int *n2);

int main()
{
    int number1 = 5, number2 = 10;

    // address of num1 and num2 is passed
    swap( &number1, &number2);

    printf("number1 = %d\n", number1);
    printf("number2 = %d", number2);
    return 0;
}

When we run the program the output will be,

Output:
number1 = 10
number2 = 5

The address of number1 and number2 are passed to the swap() function using this line of code, swap(&number1, &number2).

Then in function definition part it is declaring two pointer variables like “int *n1″ and “int *n2“,

void swap(int* n1, int* n2) {
    ........
}

When the values are changes between *n1 and *n2 inside the swap() function, then the values inside the number1 and number2 are also changed in main() function.

Due to passing of addresses from main() function to swap(), then *n1 and *n2 swapped. Hence, number1 and number2 are also swapped.

Also Notice Here, swap() function is not returning anything because its return type void.

Lingaraj Senapati

Example: Passing Pointers to Functions

#include <stdio.h>

void addOne(int* ptr) 
{
  (*ptr)++; // adding 1 to *ptr
}

int main()
{
  int* q, i = 10;
  q = &i;
  addOne(q);

  printf("%d", *q); // 11
  return 0;
}

Here, in above program we are passing pointer variable as function argument.

So, addOne() function passing pointer q from main() as an actual argument, and in the formal argument, it’s stored in a pointer variable int* ptr.

void addOne(int* ptr){
.........
}

Inside function the pointer variable increment by 1 it’s value.

*(ptr)++;

And then inside main() the value of pointer variable display in updated data.

If you find any issue and interested to rewrite it then contact us.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter