Pointer and Function in C with Examples
In C, pointers can also be used to pass function arguments and return values. When passing an argument to a function by reference, a pointer to the variable is passed instead of the variable itself. This allows the function to modify the original variable.
For example:
#include<stdio.h>
void increment(int *);
int main()
{
int a = 5;
increment(&a);
printf("%d", a); // output: 6
return 0;
}
void increment(int *x)
{
(*x)++;
}
In this example, the function "increment" takes a pointer to an integer as an argument and increments the value at that memory location. The & operator is used to pass the address of the variable "a" to the function.
Functions can also return a pointer to a variable.
For example:
#include<stdio.h.
int* get_largest(int *,int);
int main()
{
int numbers[] = {1, 2, 3, 4, 5};
int* largest = get_largest(numbers, 5);
printf("%d", *largest); // output: 5
return 0;
}
int* get_largest(int* arr, int size)
{
int* largest = arr;
for (int i = 1; i < size; i++)
{
if (*(arr+i) > *largest)
{
largest = arr+i;
}
}
return largest;
}
In this example, the function "get_largest" takes an array of integers and its size as arguments and returns a pointer to the largest element in the array.