- What is Wild Pointer in C
- What is pointer to a function in C
What is Wild pointer in C
A Pointer in C that has not been initialized till its first use is known as Wild pointer. A wild pointer points to some random memory location.
int main() { int *ptr; /* Ptr is a wild pointer, as it is not initialized Yet */ printf("%d", *ptr); }
How can we avoid Wild Pointers ?
We can initialize a pointer at the point of declaration wither by the address of some object/variable or by NULL;
int main() { int val = 5; int *ptr = &val; /* Initializing pointer */ /* Ptr is not a wild pointer, it is pointing to the address of variable val */ printf("%d", *ptr); }
What is pointer to a function in C
A pointer to a function is a pointer that stores the address of a function. Unlike regular pointers, function pointers points to code not to memory location where data is stored. We can use a function pointer to call a function which it is pointing to. Here is the Syntax and Example of function pointer.
C program to call a function using function pointer
#include <stdio.h> int getSum(int a, int b){ return a + b; } int main() { int sum; /* f_ptr is a pointer to function which takes two integer as input and returns an integer. We can use addressof operator to get the base address of any function. */ int (*f_ptr)(int, int) = &getSum; /* Now, calling getSum function using f_ptr */ sum = (*f_ptr)(2, 5); printf("%d\n", sum); return 0; }Output
7
Related Topics