Pointers & Functions in C
In this tutorial, you will learn about pointers and how to use pointers and functions in C programming.
Pointers
As we know, the pointer in C language is a variable which stores the address of another variable. i.e., direct address of the memory location. These pointers can be used to pass as arguments to functions. As pointers are used to store addresses, they can be used in functions.
Uses and Functions of Function Pointers
- The main difference between a normal pointers and a function pointer is, a function pointer points to code (address), not data.
- Unlike normal pointers, we cannot allocate and change the memory using function pointers.
- A function’s name can also be used to get functions’ address. This can be done with the help of function pointers.
- Like normal pointers, we can have an array of function pointers.
- Function pointer can be used in place of switch case.
Sample program to Pass Addresses to Functions in C programming
[maxbutton id=”1″ url=”https://coderseditor.com/?id=231″ ]
#include <stdio.h> void swap(int *p1, int *p2); int main() { int val1 = 7, val2 = 5; swap( &val1, &val2); printf("Value1 = %d\n", val1); printf("Value2 = %d", val2); return 0; } void swap(int* p1, int* p2) { int temp; temp = *p1; *p1 = *p2; *p2 = temp; }
Output
Value1 = 5
Value2 = 7
Sample program for Passing Pointers to Functions in C
[maxbutton id=”1″ url=”https://coderseditor.com/?id=232″ ]
#include <stdio.h> void addOne(int*ptr) { (*ptr)++; } int main() { int* ptr, a = 57; ptr = &a; addOne(ptr); printf("Value of adding is %d", *ptr); return 0; }
Output
Value of adding is 58