With the aid of examples, you will learn about Pointers And Functions In C in this article. You will discover how to give a pointer as an argument to a function in this article. You must have a fundamental understanding of C programming’s pointers and functions in order to comprehend this notion.
Pointers may also be supplied as an argument to a function, just like any other type of argument. To better understand how this is done, let’s look at an example.
Addresses can also be sent to functions as arguments in C programming.
We can use pointers in the functional specification to accept these addresses. Pointers are used to hold addresses, which explains why. Here’s an illustration:
Example 1: Pass Addresses to Functions
#include <stdio.h> void swap(int *n1, int *n2); int main() { int num1 = 5, num2 = 10; // address of num1 and num2 is passed swap( &num1, &num2); printf("num1 = %d\n", num1); printf("num2 = %d", num2); return 0; } void swap(int* n1, int* n2) { int temp; temp = *n1; *n1 = *n2; *n2 = temp; }
The output from running the program is:
num1 = 10
num2 = 5
Swap(&num1, &num2); passes the addresses of num1 and num2 to the swap() method.
These arguments are accepted by pointers n1 and n2 in the function specification.
void swap(int* n1, int* n2) { ... .. }
Changes made to *n1 and *n2 inside the swap() method also affect num1 and num2 inside the main() function.
The swap() function swapped the values of *n1 and *n2. As a result, numbers 1 and 2 are also switched.
The return type of swap() is void, thus you can see that it doesn’t produce anything.
Example 2: Passing Pointers and Functions In C
#include <stdio.h> void addOne(int* ptr) { (*ptr)++; // adding 1 to *ptr } int main() { int* p, i = 10; p = &i; addOne(p); printf("%d", *p); // 11 return 0; }
In this case, the value initially saved at p, *p, is 10.
The pointer p was then provided to the addOne() method. The addOne() function provides this address to the ptr pointer.
Using (*ptr)++; inside the code, we raised the value kept at ptr by 1. Since the addresses of ptr and p pointers are identical, the value of *p inside of main() is also 11.
You May Like: