Pointers in C programming

Pointers in C programming with examples

Pointers in C are a variable that stores the address of another variable. Every variable is a memory location and it has its address defined which can be accessed using the ampersand (&) operator. ‘&’ denotes an address in memory. Variable can be of type int, char, array, or any other pointer.

Define a Pointer in c

int n = 5;   
int* p = &n;

 

 

Declaring pointers in C programming

The * operator called Dereference operator followed by the name of the pointer gives the value stored in the address pointed by the pointer. It is also called an indirection pointer used to dereference a pointer.

Syntax

int *a;//pointer to int  
char *c;//pointer to char  

Program of declaring a pointer in C

#include<stdio.h>  
int main(){  
int number=50;    
int *p;      
p=&number;    
printf("Address of p variable is %x \n",p);      
printf("Value of p variable is %d \n",*p);    
return 0;  
}    

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

 

 

NULL Pointer in C

A pointer that is assigned NULL has known a null pointer. A null pointer does not point to an object or a function.

Program of the null pointer in C

#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );
 
   return 0;
}

Output

The value of ptr is 0

 

Pointers and Arrays

A pointer that points to the starting of an array can access the array by using either pointer arithmetic or array-style indexing. Pointers and arrays support the same set of operations, with the same meaning for both. The main difference is that pointers can be assigned new addresses, where arrays will always represent the same address blocks.

Pointer to Pointer

It is used to store the address of a variable. It reduces the access time of a variable. We can also define a pointer to store the address of another pointer. Such a pointer is called a double pointer (pointer to pointer).

 

Syntax of a pointer in C

int **p;

Program of pointer to a pointer in c

#include<stdio.h>  
void main ()  
{  
    int a = 5;  
    int *p;  
    int **pp;   
    p = &a;        // pointer p is pointing to the address of a  
    pp = &p;       // pointer pp is a double pointer pointing to the address of pointer p  
    printf("address of a: %x\n",p); // Address of a will be printed   
    printf("address of p: %x\n",pp); // Address of p will be printed  
    printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be printed  
    printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer stoyred at pp  
}  

Output

address of a: d26a8734
address of p: d26a8738
value stored at p: 5
value stored at pp: 5

 

Also read, C-Function

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *