Wild pointers

A pointer which has not initialized to anything (not even NULL) is known as a wild pointer. The pointer may be initialized to a non-NULL garbage value that may not be a valid address.

int main()
{
   int a;
   int*ptr; //wild pointer  or bad pointer

   return 0;
}

NULL pointer

A NULL pointer is a pointer which is pointing to nothing. In case, if we don’t have an address to be assigned to a pointer, then we can simply use NULL.

#include <stdio.h>
int main()
{
  int a,b;
  int*ptr=NULL;    //int*ptr=(int*)0;
  
  if(ptr==NULL)   //if(ptr==(int*)0)
  {
    ptr=&a;
    a=10;
  }
  if(ptr==NULL)
  {
    ptr=&b;
    b=20;
  }
  printf("\nvalue of *ptr:%d",*ptr);
  return 0;
}

Output:

[quote]

value of *ptr:20

[/quote]

#include <stdio.h>
int main()
{
  int a,b;
  unsigned char*ptr=NULL;
  ptr=&a;
  a=511;
  
  b=*ptr;

  printf("\n%d %d %d",a,b,*ptr);

  *ptr=10;

  printf("\n%d %d %d",a,b,*ptr);
  return 0;
}

Output:

[quote]

511 255 255                                                                                                                                                 
266 255 10  

[/quote]

#include <stdio.h>
int main()
{
   int i;
   int*iptr=NULL;   //int*iptr=(int*)0;
   float f;
   float*fptr=NULL;  //float*fptr=(float*)0;
   char ch;
   char*cptr= NULL;  //char*cptr=(char*)0;

   iptr=&i;
   i=11;
   printf("\n%d %d",i,*iptr);

   fptr=&f;
   f=12.22;
   printf("\n%f %f",f,*fptr);

   cptr=&ch;
   ch='A';
   printf("\n%c %c",ch,*cptr);
   return 0;
}

Output:

[quote]

11 11                                                                                                                                                       
12.220000 12.220000                                                                                                                                         
A  A    

[/quote]

void pointer

void pointer is a specific pointer type ‘void *‘ – a pointer that points to some data location in storage, which doesn’t have any specific type. void refers to the unknown type. Basically, the type of data that it points to is can be any. If we assign the address of char data type to void pointer it will become char pointer, if int data type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any value.

#include <stdio.h>
int main()
{
   int i;
   float f;
   char ch;
   void*ptr = NULL; //void*ptr=(void*)0;
   
   ptr=&i;
   i=11;   //*(int*)ptr=11;
   printf("\n%d %d",i,*(int*)ptr);

   ptr=&f;
   f=12.22;  //*(float*)ptr=12.22;
   printf("\n%f %f",f,*ptr);

   ptr=&ch;
   ch='A';   //*(char*)ptr='A';
   printf("\n%c %c",ch,*(char*)ptr);
   return 0;
}

Leave a Reply

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