How to Declaring a pointer?

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

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

Pointer Syntax

  • Here is how we can declare pointers.
int* p;
  • Here, we have declared a pointer p of int type.
  • You can also declare pointers in these ways.
int *p1;int * p2;
  • Let's take another example of declaring pointers.
int* p1, p2;
  • Here, we have declared a pointer p1 and a normal variable p2.

Pointer example


An example of using pointers printing the address and value is given below.
https://mskuthar.blogspot.com/
Declaring a pointer
  • As you can see in the figure above, the pointer variable stores the number variable address i.e. fff4. The number variable value is 50 but the pointing variable p address is aaa3.
  • By the help of * (indirection operator), we can print the value of pointer variable p.
  • Let's see the pointer example as explained for above figure.

For Example:-

#include <stdio.h>      
#include <conio.h>    

void main(){      
int number=50;  
int *p;    
clrscr();  
p=&number;//stores the address of number variable  
      
printf("Address of number variable is %x \n",&number);  
printf("Address of p variable is %x \n",p);  
printf("Value of p variable is %d \n",*p);  
  
getch();      
}   

Output

Address of number variable is fff4
Address of p variable is fff4 

Value of p variable is 50

NULL Pointer

  • A pointer that is not assigned any value but NULL is known as NULL pointer. 
  • If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.   
int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

Let us take an example
#include <stdio.h>
#include <conio.h>
int main()
{
   int* pc, c;
   
   c = 22;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c);  // 22
   
   pc = &c;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 22
   
   c = 11;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 11
   
   *pc = 2;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c); // 2
   return 0;
}
Expected Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Post a Comment

Previous Post Next Post