Monday, 12 August 2019

A Detail Guide of Function Pointer in C with programming example

Function Pointer in C


In the C programming language, a function pointer is an important pointer tool. Most of the time, the function pointer is misunderstood and ignored by the people. Because of the inappropriate explanation of declaration, and dereferencing of a function pointer.

Misconception on the function pointer creates various hidden issues in your project, which takes a lot of time in resolving.

Function Pointer in C is a very important and difficult topic to understand. Very few people understand and utilize this concept.

See Also: Types of Pointers in C

What is Function Pointer in C?

Function Pointer is similar to the other pointers in C. The difference between C function pointer and in other pointers is that function pointer points to a function instead of the variable.

Source: mycodeschool 

In other words, the function pointer points to the address of a function and these function used in the program whenever needed.

Declaration of Function Pointer in C

Declaration of a function pointer is very easy. It looks complicated, but once you start learning it becomes very easy for you.

See Also: Dangling Pointers in C

Declaration of a function pointer is similar to the C functions. So, it needs parameter list, declaration name, and return type. You should always remember at the time of declaration the name of the function pointer is preceded by the '*' (asterisk) symbol and encloses in parenthesis.

Syntax

return type (*Name_of_Function_Pointer) (argument_list);

For instance,
int (*add) (int*, int*);

In the above example, 'add' is a name of function pointer which takes two parameters (int*, int*) and returns int.

See Also: Double Pointer

In the declaration of function pointers in C, brackets play a significant role. In the above example, if brackets are eliminated, then the meaning of the above statement will completely change, and we get int *add (int*, int*). It is a declaration of function which takes (int*, int*) as parameters and returns int.

Initialization of Function Pointer in C

Working of a function pointer is similar to the pointers. We need to define function pointers after the declaration of it.

A function pointer is initialized to the address of a function, but the signature of the function pointer should be the same as the function. For instance, a function pointer taking two parameters and returns an integer value. This pointer pointing to the address of a function 'SUB' is used in the subtraction of two numbers.

#include <stdio.h>
#include <stdlib.h>
int SUB (int a, int b) //Function definition
{
int c;
c = a - b;
return c;
}

We define a function which prints the output of subtraction of two numbers when the function SUB is called.

int main()
{
int q = 0;
int (*p) (intint) = NULL; //Declaration of function pointer
p = SUB; //Initialization of Function pointer
q = (*p) (50, 20); //Calling the function pointer
printf ("\n\nSubtraction of two number = %d\n\n", q);
return 0;
}

Output
Subtraction of two number = 30

Some Essential Points for Pointer to function

We are discussing some important points for function pointer in C.

A) Just like pointers, function pointers cannot allocate de-allocate memory. It is used to point the address of the function. So, if we allocate memory, then there is no need for a function pointer.

int (*ptr) (int,int) = malloc(sizeof(ptr)); // No use

B) A function name is used to get the address of the function. The function name is sufficient to get the address of the function, no need to use '&' (ampersand operator) to get the address of the function.

ptr = SUB;
OR
ptr = &SUB;

C) You can call the function with the help of function pointer after initialization. Let's understand the function calling,

1) Name of the function pointer, ptr
2) Pointer to function is like normal pointers, but the only difference between function pointer and the normal pointer is that function pointer pointing to the function instead of variable. That's why we use '*' operator before the name of the function pointer to take the value of the function pointer. *ptr
3) Call the function with parameters, (*ptr)(50,60);

C Program helps you to understand the functioning of the pointer to function.
#include <stdio.h>
#include <stdlib.h>
//Function definition to subtract two numbers.
int SUB (int a, int b);
{
return (a-b);
}
int main()
{
int c;
int (*ptr)(int,int) = NULL; //Declaration of function pointer "ptr"
ptr = SUB; //Initialization of function pointer (Assign the address of function "SUB" to the Function pointer "ptr")
c = (*ptr) (60,50); //Function Calling
printf ("Subtraction of two numbers is %d\n", 10);
return 0;
}

Output
Subtraction of two numbers is 10

D) You can use the function pointer in C with the comparison operator (!= or ==). These operators help you to find out function pointer is initialized or not, and it considered as a good practice.
If the valid address is not assigned to the function pointer and application wants to execute the function pointer then you will get Blue screen of death (BSOD), or system hangs issues. So, always check the validity of the function pointer. For instance,

if (add==NULL)
{
return invalid;
}
else
{
(*add) (state);//Calling function
}

E) In the C programming language, function pointer can be used as an argument into the function. Let's understand with the help of C program how to function pointer is used as the argument into the function.

#include <stdio.h>
typedef int (*fpatr)(int,int); //Function Pointer
//Function Pointer as arguments
int mul_operation (int value1, int value2, fpatr cal)
{
int ret_value = 0;
ret_value = cal (value1, value2);
return ret_value;
}
//Function for multiplication of two numbers
int mul (int value1, int value2)
{
int value3;
value3 = value1*value2;
return value3;
}
int main()
{
int value1=0;
int value2=0;
int out=0;
printf ("Enter the data");
scanf ("%d%d", &value1, &value2);
out = mul_operation (value1,value2,mul);
printf ("Multiplication of two numbers is %d\n",out);
return 0;
}

Output
Enter the data 10 20
Multiplication of two numbers is 200

F) Learn how a function can return a function pointer in C with the help of program example.

#include <stdio.h>
//type declaration of function pointer
typedef int (*pfatr)(int, int);
//function for the addition of two number*/
int Add (int value1 ,int value2)
{
int value3;
value3 = value1+value2;
return (value3);
}
//function for the subtraction of two number
int Sub (int value1 ,int value2)
{
return (value1 - value2);
}
//function for the multiplication of two number
int Mul (int value1 ,int value2)
{
return (value1 * value2);
}
//Function for the division of two number
int Div (int value1, int value2)
{
int value3;
value3 = value1/value2;
return value3;
}
//Return function pointer
pfatr Operations (int Choice)
{
//function pointer
pfatr Function = NULL;
switch (Choice)
{
case 1:
Function = Add;
break;
case 2:
Function = Sub;
break;
case 3:
Function = Mul;
break;
case 4:
Function = Div;
break;
}
return Function;
}
int main (void)
{
int value1 = 0;
int value2 = 0;
int Choice = 0;
int Result = 0;
pfatr Function = NULL; //function pointer
printf ("Enter Data \n\n");
scanf ("%d%d",&value1,&value2);
printf ("Enter 1 for the Addition \n\n");
printf ("Enter 2 for the Subtraction \n\n");
printf ("Enter 3 for the Multiplication \n\n");
printf ("Enter 4 for the division \n\n");
scanf ("%d",&Choice);
Function = Operations (Choice);
//verify the pointers
if (Function != NULL)
{
Result = (*Function) (value1,value2);
printf ("Result is %d\n\n",Result);
}
else
{
printf ("Enter the choice\n");
}
return 0;
}

Output
Function Pointer in C

Use of Array of Function Pointer in C

The C array of function pointers is similar to the pointers. You can access the array of function pointer using an array index. For instance,

#include <stdio.h>
#include <stdlib.h>
int Add (int value1 ,int value2)
{
int value3;
value3 = value1+value2;
return (value3);
}
//function for the subtraction of two number
int Sub (int value1 ,int value2)
{
return (value1 - value2);
}
//function for the multiplication of two number
int Mul (int value1 ,int value2)
{
return (value1 * value2);
}
//Function for the division of two number
int Div (int value1, int value2)
{
int value3;
value3 = value1/value2;
return value3;
}
int main()
{
int ret_value =0;
//Declaration of array of function pointers
int (*fpatr[4])(int,int) ={Add,Sub,Mul, Div};
//With the help of index of array, calling addition function 'Add'
ret_value = (*fpatr[0])(30,10);
//Prints the output of addition of two numbers
printf ("Addition of two numbers =%d\n\n", ret_value);
//With the help of index of array, calling subtraction function 'Sub'
ret_value = (*fpatr[1])(30,10);
//Prints the output of Subtraction of two numbers
printf ("Subtraction of two numbers =%d\n\n", ret_value);
//With the help of index of array, calling multiplication function 'Mul'
ret_value = (*fpatr[2])(30,10);
//Prints the output multiplication of two numbers
printf ("Multiplication of two numbers =%d\n\n", ret_value);
//With the help of index of array, calling division function 'Div'
ret_value = (*fpatr[3])(30,10);
//Prints the output of division of two numbers
printf ("Division of two numbers =%d\n\n", ret_value);
return 0;
}

Output
Addition of two numbers = 40
Subtraction of two numbers = 20
Multiplication of two numbers = 300
Division of two numbers = 3

Use of typedef with the Function Pointer

Typedef makes the declaration of function pointer in C easy. For instance, In the above C program, declaration of the array of function pointers makes the program a little bit complex. But typedef can make the programming easier.

//typedef of the array of function pointers,
typedef int (*fpatr[4])(int,int);
'fpatr' store the address of four functions.
fpatr operations = {Add, Sub, Mul, Div};

Declare Function Pointers in the Structure

C does not have member functions like C++. In the C programming language, structure only contains data, not function. With the help of function pointer, a structure can contain functions. For instance,

struct fpatr
{
int value;
void (*fpk) (char *data1, int data2);
int (*fpdm) (char* data3);
}End;

Function Pointer as Callback Function

In the operating system (like windows), KMDF (Kernel Mode Driver) use various callback function for the play, and device preparation. This callback function is used for particular events, but we should register this function with the help of function pointer in C.

When an executable code is passed as an argument is known as a callback. In general, if reference of a function is passed to another function as an argument to call function, then it will be called as a callback function.

In the C language, a callback function is called through a function pointer.

C program demonstrates the working of the callback function.
#include <stdio.h>
#include <stdlib.h>
int add (int value1, int value2)
{
int value3;
value3 = value1+value2;
printf ("Addition of two number is %d\n", value3);
}
int CB_fun (int(*ptr) (int,int))
{
(*ptr)(20,10); //Callback to add
}
int main()
{
int value1, value2;
int (*ptr)(int,int) = &add;
//Calling function CB_fun and passing address of the add function as an argument
CB_fun(ptr);
return 0;
}

Output
Addition of two number is 30

Monday, 5 August 2019

Learn Various Types of pointers in C


Types of pointers in c

Pointers are used to hold the address of another variable of the same data type like int, char, array etc. As we know, every variable has a memory location and every memory location has a memory address. You can access the memory address by using the ampersand (&) operator. C program which prints the address of the variable.
#include <stdio.h>
int main()
{
    int a,b; // Declare variable a and b
    printf ("Address of variable a is %u\n", &a);
    printf ("Address of variable b is %u\n",&b);
    return 0;
}

Output
Address of variable a is 2686748
Address of variable b is 2686744


See Also: Function Pointer in C


int q = 10; //declaration and initialization of variable


Types of pointers in C


int *p;       // declaration of pointer variable


Types of pointers in C

p = &q    // initialization of pointer variable 'p'


types of pointers in C


Pointer variable 'p' keep the address of 'q' that is 2000. To access the value of the variable 'q', use *p (asterisk p).


Types of pointers in C

In the previous article, we discussed what is Pointers in C and how to use pointers. In this article, we will discuss various types of pointers in C.


See Also: Double Pointer in C/Pointer to Pointer in C

What is a NULL pointer in C?

This is considered good practice if you assign a null value to pointer variables. When you don't have a valid address to assign to the pointer variables then you can use NULL. A pointer which is initialized with NULL value is known as a NULL pointer in C. 

A NULL pointer is a predefined macro and its value is 0 which defined in the 'stdio.h', 'alloc.h', 'stdlib.h', 'mem.h', 'stddef.h' header files. 

Syntax
<data type> *<Variable_Name> = NULL;
For instance, int *p = NULL;

In the above example, pointer p is an integer type pointer variable which is initialized with NULL and pointer *p is known as a NULL pointer.

char *p = '\0';
float *p = (float *)0;
double *p = NULL;

#include <stdio.h>
int main()
{
int *p=NULL;
if (p!=NULL)
{
printf ("Pointer p is not a NULL Pointer");
}
else
{
printf ("Pointer p is a NULL Pointer");
}
return 0;
}

Output
Pointer p is a NULL pointer

Wild Pointer in C

Those pointer variables which are declared but not initialized with any address is known as a wild pointer. These pointer variables contain garbage value.

Difference between NULL pointer and the wild pointer is that NULL pointer is initialized with zero whereas, a wild pointer is uninitialized and consist garbage value. Below mention, C program which helps you to understand the concept of the wild pointer in C.
#include <stdio.h>
int main()
{
int *a; //Wild Pointer
int b=10; // Initialization of variable b
//After initialization pointer is not a valid pointer
a = &b;
return 0;
}

Void Pointer in C

A void pointer is an untyped pointer i.e. those pointers which are the point to any variable of any data type that is not associated with any particular data type. It can store the address of any data type. This pointer is also known as the generic pointer or general-purpose pointer because it can store the address of any data type.

Declaration of a void pointer is similar to normal pointer only difference is that void keyword is used instead of data type (int, float, char, double etc.)

Syntax
void <name_of_variable>
For instance, void *p;

C program helps you to understand the working of the void pointer in C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 5;
char b = 'd';
void *p = &a; //Void pointer 'p' holds the address the of integer variable 'a'.
p = &b; //Assign the address of character varaiable 'b' to void pointer 'p'
return 0;
}

Dereferencing a Void Pointer in C
Accessing the value of that address which is stored in the pointer variable is called dereferencing. We need a type-casting because the void pointer is not associated with any data type.
#include <stdio.h>
int main ()
{
void *p; // Declare void pointer 'p'
int q =10; //Initialize integer variable 'q'
p = &q; //Assign the address of variable 'q' to the pointer 'p'.
printf ("*p=%d\n", *p);
return 0;
}

Output
When we will compile the above code then we will get an error because in the above tried to dereference the void pointer without type-casting.


Type-cast  the void pointer

#include<stdio.h>
void main ( )
{
int w=41;
float x=49.5;
char y='a';
void *p;
// *((int*)p)) is type-casting of pointer variables
p=&w;
printf ("Integer variable is %d\n",*((int*)p));

p=&x;
printf ("Float variable is %f\n",*((float*)p));

p=&y;
printf ("Character variable is %c\n",*((char*)p));

}

Output
41
49.500000
a

Dangling Pointers in C

When a pointer pointing to freed or deleted memory location then these pointers are known as dangling pointers. These pointers are created when the object is de-allocated or deleted without modifying the value of the pointer. So, the pointer still points to the de-allocated or freed memory location.


See Also: What are Tokens in C?


The three different ways created Dangling pointers in C:
1) De-allocation of memory
2) Function Call
3) Variable goes out of scope

1) De-allocation of memory

//Dangling pointer is created when the pointer 'p' points to the memory after deallocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *p;
    p=(int*)malloc(sizeof(int));
    free(p); //After free call, Pointer 'p' become dangling pointer
    p = NULL; //No more dangling pointer
    return 0;
}

2) Function Call

//If local variable is not static and the pointer 'p' become dangling pointer if it still pointing to local variable.
#include <stdio.h>
int *fun(); //Declaration of function fun()
int main()
{
int *ptr=fun();
printf ("%d\n", *ptr);
return 0;
}
//Definition of function fun()
int *fun()
{
int a =10;
return &a;
}

Output 
Garbage Value

Pointer 'ptr' doesn't become dangling if 'a' is static.

#include <stdio.h>
int *fun(); //Declaration of function fun()
int main()
{
int *ptr=fun();
printf ("%d\n", *ptr);
return 0;
}
//Definition of function fun()
int *fun()
{
static int a =10;
return &a;
}

Output
10

3) Variable goes out of scope

#include <stdio.h>
int main()
{
    int *p;

    //block
    int a =10;
    p = &a;
    }

    {
        printf ("a=%d\n", *p);  //Here, p is a dangling-pointer
    }
    return 0;
}

Avoid the Creation of Dangling Pointer

Generation of Dangling Pointer can be avoided by initializing pointer to NULL after freed or deleted the memory. After assigning NULL to the pointer means pointer not pointing to anything (memory address). Below mention C program helps you to understand that how NULL can avoid dangling pointer.
#include <stdio.h>
#include <stdlib.h>
int main();
{
    int *p; // Declaration of pointer
    int a =10; // Declaration of variable 
    p = &a; //Initialization of pointer
    free(p); // Pointer p become Dangling
    p = NULL;
    return 0;
}

OLD Pointers


Near, far and huge pointers are designed for MS-DOS operating system which is based on the 8085 microprocessor.  These pointers are used only on the 16-bit machine, so, nowadays, they are not used.

Near pointers in C 

Near pointer is used to store 16-bit address on the data segment, code segment or stack segment, only on the 16-bit machine. At a time, it can only access 64Kb data. You can not access near pointer beyond the segment like text and video memory. Size of this pointer is 2 byte. "near" is a keyword which is used to make any pointer as a near pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a =10; //declaration of variable
    int near* p; //declaration of near pointer p
    p=&a; //Assign address of a to the pointer p
    printf ("size of near pointer p is %d\n", sizeof(p));
    return 0;
}

Output
4

Far pointers in C 

This pointer is used to store 32-bit data and can access the memory outside the current segment. To use this, the compiler allocates a segment register to store segment address, then another register to store offset within the current segment. Size of this pointer is 4-byte.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a =10; //declaration of variable
    int far* p; //declaration of near pointer p
    p=&a; //Assign address of a to the pointer p
    printf ("size of far pointer p is %d\n", sizeof(p));
    return 0;
}

Output
4

Huge pointers in C 

These pointers are of 32-bit and can access the memory outside this segment. In far pointer, a segment is fixed but in the huge pointer, we can increase or decrease the segment portion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a =10; //declaration of variable
    int huge* far* p; //declaration of near pointer p
    p=&a; //Assign address of a to the pointer p
    printf ("size of pointer p is %d %d %d\n", sizeof(p), sizeof(*p),sizeof(**p));
    return 0;
}

Output
4 4 1

Normalization of Huge pointers

Turbo C compiler works on 8085 microprocessor. In 8085 microprocessor, the physical address of memory is 20 bit long. The process to convert 32-bit huge address into 20-bit physical address is known as normalization.




Read Also

Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free() and Realloc()
What is Structure in C?
What are Storage Classes in C?

Monday, 29 July 2019

What is Pointers in C & how it works?

A pointer is a variable in the C programming language which holds the address of another variable of the same data type. For instance, an integer variable contains an integer value; however, an integer pointer holds the address of integer variable. 

Pointers in C have derived data types. Whenever a variable is initialized in the C programming language, memory is allocated to it which stores the value of the variable. With the help of ampersand (&), we can find out the address of that variable. Below mention, C  program helps you to understand "How to access the address of a variable using the ampersand (&)."


See Also: Types of pointers in C 


#include <stdio.h>
int main ( )
{
int a = 12;
printf ("Value of a=%d\n", a);
printf ("Address of a=%x\n", &a);

Output
Value of a =12
Address of a = 28ff1c (This output is different for different runs because the variable is stored at a different memory location in different runs.)



Whenever we declared a variable in the C programming language, then memory is allocated to that variable. Each memory location has its address, as we saw in the above program. Assume the variable 'i' is stored at memory location 5698 with the value '12'.

See Also: Pointer to Pointer

int i = 12;

Pointers in C














Declaration and Initialization of Pointers in C

Just like variables, pointers are also declared before using in the program. Pointer's name can be anything, but they should obey the rules of C.

See Also: Function pointer in C

Syntax to declare pointer variables
data type  *pointer_name;

For example
int *w//Integer data type (w) pointer variable
float *x; // Float (x) pointer variable
char *y; //Character data type (y) pointer variable.

With the help of asterisk (*) operator, we can access the value of the pointer. Because no value is assigned to these variables, so it contains a garbage value, and therefore they point to a memory location as shown in the figure, 

int *z

Pointers in C









Initialization of pointer variables

There are two ways to initialize pointer variables. You can get the memory location of the variable with the help of the reference operator (&), or you can directly assign one pointer variable to other pointer variables.

int   q             // Variable declaration

Pointers in C








Variable 'q' is stored at memory location 2000, which consists a garbage value.

int   *p           // Pointer variable declaration


Pointers in C









Pointer variable 'p' is stored at memory location 3000 with garbage value.

p = &q;           // Initialization of pointer variable



Pointers in C









After initialization, the pointer variable 'p' holds the address of the variable q, which is 2000.

int *p = q//Initialize pointer using another pointer

How to access a variable through the pointer variable?

Once an address of a variable is assigned to a pointer, the question arises that how to access the value of the variable using the pointer? This is done by using a unary operator (*) asterisk. This is also known as indirection operator or dereferencing operator.

#include <stdio.h>
int main ( )
{
    // Declaring variable and pointer variable
    int a, *q;

    // Initialize variable a
    a = 12;

    // Initialize pointer variable q
    q = &a;

    printf ("%d\n", *q);          //This will print the value of a
    printf ("%d\n", *&a);     // This will print the value of a
    printf ("%d\n", &a);     // This will print the address of a
    printf ("%d\n", p);       // This will print the address of a
    printf ("%d\n", &p);   // This will print the address of p


    return 0;

}

Size of Pointers in C

In the above section, we discussed what a pointer is in C?  We will discuss the size of the pointer, why the size of the pointer changes from one compiler to another compiler. 


Size of pointers in C






Above figure shows that size of integer and size of the pointers in c varies from compiler to compiler. If the compiler is 16-bit, it occupies 2 bytes, and if it's a 32-bit compiler, it occupies 4 bytes integer and pointer both are same. The reason why the pointer's size depends on the size of the compiler. 16-bit compiler contains 2^16 memory location.

Total location in the 16-bit compiler would be 2^16 = 65,536.

int a = 134;

The value of the integer 134 will be allocated in memory location between 0 to 65,536.

Size of pointers in C











int *ptr;


size of pointers in C











Because the pointer ptr is also the type of integer, the memory location will be allocated between 0 to 65,536.

ptr =&a;

Now, the pointer variable 'ptr' holds the address of the integer variable 'a.'

Size of pointers in C









Program to calculate the size of pointers in C.

#include <stdio.h>
#include <conio.h>
int main ( ) 
{
int a = 32;
char ch = 'd';
int *b;
char *cp;
b = &a;
cp = &ch;
printf ("size of pointer b is %d and cp is %d\n", sizeof(b), sizeof(cp));
return 0;
}

You all might be thinking that its output will be 1 byte for character pointer 'cp' and 4 bytes for the integer pointer 'b.' But this is not true, both the character pointer and the integer pointer will have the size of 4 bytes. Why do so, let's talk about it.

Size of pointers in C









Whenever you declare a normal variable, size varies from one data type to another type because the type of data you are storing is different.
But, when we are declaring character pointer, integer pointer and float pointer holding the address of variable 'ch,' 'a' and 'd.'

char *c = &ch;


i.e., character pointer 'c' holds the address (2034) of 'ch.'

int *= &a;

and integer pointer 'b' holds the address (5896) of the variable 'a.'

double *w = &d;

Pointer variable 'w' holds the address (9325) of the variable 'd'.

Using pointer variables always we are storing the same type of data. All pointer variables hold the address of a normal variable; it is not holding the data, so, what it is holding? It is holding the address 2034, 5896 and 9325. Pointer variable always holds the address, so, it always occupies 2 bytes memory. Pointer size is always fixed because it is holding address instead of data.

Arithmetic Operation on Pointers

At the time of the program, we need to perform an arithmetic operation on the pointer. But before using the arithmetic operation on the pointer, it is essential to understand the limitation of arithmetic operators with the pointers. The C programming language has a lot of arithmetic operators, but, we can only use increment or decrement operators with pointers.

The arithmetic operation can be performed on pointers. A pointer can be:
Incremented
Decremented
An integer value can be added to the pointer
An integer value can be subtracted from the pointer

When you are working with pointers, you should take care of the priority rule.
1) The operator '*' and '&' have the same priority.
2) In the same statement, the operators '*', '&', '++', '--' are evaluate from right to left.

Increment/Decrement Operation on Pointer

When we increment or decrement the pointer, the pointer points to the next/previous memory location. Below mention C program helps you understand the working of increment operation on pointers in C.

#include <stdio.h>
int main()
{
int arr[3]={10,20,30}; //Initialize Array 'arr' with three elements
int *ptr; //Declared Pointer 'ptr'
int i; //Declare integer variable 'i'
ptr=&arr; //Assigning initial address of array 'arr' to pointer 'ptr'
for (i=0;i<3;i++)
{
printf ("Value of pointer *ptr =%d\n", *ptr);
printf ("Value of ptr =%p\n", ptr);
ptr++;
}
return 0;
}


Output
Value of pointer *ptr = 10
Value of ptr = 0028FF0C
Value of *ptr=20
Value of ptr =0028FF10
Value of *ptr=30
Value of ptr = 0028FF14


C program helps you to understand decrement operation on pointers in C
#include <stdio.h>
int main()
{
int arr[3]={10,20,30};
int *ptr;
int i;
ptr=&arr;
for (i=0;i<3;i++)
{
printf ("Value of pointer *ptr =%d\n", *ptr);
printf ("Value of ptr =%p\n", ptr);
ptr++;
}
printf ("\n\n");
for (i=0;i<=3;i++)
{
printf ("Value of pointer *ptr =%d\n",*ptr);
printf ("Value of ptr =%p\n",ptr);
ptr--;
}
return 0;
}


Output
Value of pointer *ptr = 10
Value of ptr = 0028FF0C
Value of *ptr=20
Value of ptr =0028FF10
Value of *ptr=30
Value of ptr = 0028FF14
Value of pointer *ptr= 30
Value of ptr = 0028FF14
Value of *ptr=20
Value of ptr =0028FF10
Value of pointer *ptr = 10
Value of ptr = 0028FF0C

Comparison of Pointers in C

You can compare two pointers using relational operator. Six types of comparison operation you can performed '<', '>', '<=', '>=", '==', '!=' .


C program demonstrates the comparison of pointers.
#include <stdio.h>
int main()
{
int arr[3]={10,20,30}; //Initialize array
int *ptr, *ptr1; // Declare pointer 'ptr' and 'ptr1'
ptr=&arr[0]; //Assign address of 0th element i.e. arr[0] to pointer 'ptr'
ptr1=&arr[2]; //Assign address of 2nd element i.e. arr[2] to pointer 'ptr1'
if (ptr == ptr1)
{
printf ("Both pointers points to the same memory location");
}
printf ("Both pointers point to different memory location\n");
return 0;
}

Output
Both pointers point to different memory location.


Pointers and Arrays

Elements of the array can be accessed using the index, but pointers replaced it. Pointers make access of each element easier. In the C programming language, pointer and array are close to each other. Name of the array is the first element of the pointer.

Program demonstrates the Array name as pointers in C.#include <stdio.h>int main()
{

int arr[3]={10,20,30};
int *ptr,i;
ptr = arr; //Assign address of array to pointer ptr
//Or you can assign address of arr to pointer ptr, ptr=&arr[0];
for (i=0;i<3;i++)
{
printf ("Value of ptr %d\n", *ptr);
ptr++;
}
return 0;
}

Output
Value of ptr 10
Value of ptr 20
Value of ptr 30

Pointers and Strings

Strings are array of characters, ended with null character ‘\0’. Let see, how to access elements of strings using pointers.

#include <stdio.h>
#include <string.h>
int main()
{

char str[]="HELLO"; //Declare a string
int l,i;
char *ptr; //Declare pointer
l=strlen(str); //Calculate length of string
printf ("%d\n",l);
ptr = &str[0]; //Assign initial address to pointer
for (i=0;i<l;i++)
{printf ("Value of pointer %c\n", *ptr);
ptr++;
}
return 0;
}

Output
Value of pointer H
Value of pointer E
Value of pointer L
Value of pointer L
Value of pointer O

Common Mistakes in Pointers in C

Some of the mistakes that most programmers do.

Omitting Pointer

int *ptr1,ptr2;
In the above statement, integer pointer *ptr1 and integer ptr2 is declared. But the intention is to declare Pointer ‘*ptr1’ and pointer ‘*ptr2’. So, the correct statement is,
int *ptr1, *ptr2;
It is the smallest mistake done by the programmers.

Uninitialized Pointer

When a programmer is not assigning a valid address to the pointer before using it. Or a programmer tries to assign a value to the uninitialized pointer then we will get the runtime error.
#include <stdio.h>int main()
{int *ptr; //Declare Pointer 'ptr'
*ptr = 20; //Assigning value to the pointer 'ptr'
printf ("Value %d\n", *ptr);
return 0;
}

 Comparison of Pointers in C

When programmer try to compare two different pointer which is pointing to different memory. We can compare the pointer if they pointing to the same array.
#include <stdio.h>
#include <string.h>

int main()
{char str[7]="WORLD";
char str1[7]="HELLO";
char *ptr1, *ptr2;
ptr1=str; //Assigning the initial address of array a[] to the pointer 'ptr1'
ptr2=str1; //Assigning the initial address of array b[] to the pointer 'ptr2'
if (ptr1>ptr2) //Compare Pointer ptr1 and ptr2 (iilegal statement)
{//statement
}return 0;
}

Ilegal Indirection

Whenever we declare a pointer or use a pointer, we need to be aware which value is used by pointers in c. Assume, malloc function is used to allocate memory. This malloc function allocates memory block to the pointer.
*int ptr = malloc(sizeof(int)); //Invalid statement
The above statement is incorrect. The correct method to allocate memory is,
int ptr=malloc(sizeof(int)); //Valid statement

Pointer Pointing Invalid Address

A run-time error is created if pointer pointing to the invalid memory address.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr; //Declare pointer variable 'ptr'
free(ptr); // Free the allocated address
*ptr=30; //Assigning value to the pointer 'ptr'
printf ("Value %d\n",*ptr);
return 0;
}