C pointer mistakes

Common Pointer Mistakes in C while using Pointer in C Programming

Pointer is used to store the address of a variable. Pointer Variable stores the address of variable.Here are some of the Common mistakes committed by Novice programmer.

A. Assigning Value to Pointer Variable

int * ptr , m = 100 ;
      ptr = m ;       // Error on This Line

Correction :

  • ptr is pointer variable which is used to store the address of the variable.
  • Pointer Variable “ptr” contain the address of the variable of type ‘int’ as we have declared pointer variable with data type ‘int’.
  • We are assigning value of Variable to the Pointer variable, instead of Address.
  • In order to resolve this problem we should assign address of variable to pointer variable

Write it like this -

ptr = &m ;

B. Assigning Value to Uninitialized Pointer

int * ptr , m = 100 ;
*ptr = m ;            // Error on This Line
  • “ptr” is pointer variable.
  • “*ptr” means “value stored at address ptr“.
  • We are going to update the value stored at address pointed by uninitialized pointer variable.

Instead write it as -

      int * ptr , m = 100 ,n = 20;
      ptr = &n;
      *ptr = m ;
  • Firstly Initialize pointer by assigning the address of integer to Pointer variable.
  • After initializing pointer we can update value.”.

C. Not De-referencing Pointer Variable

De-referencing pointer is process of getting the value from the address to whom pointer is pointing to.

int * ptr , m = 100 ;
ptr =  &m ;
printf("%d",ptr);     

D. Assigning Address of Un-initialized Variable

int *ptr,m;
ptr = &m;     

E. Comparing Pointers that point to different objects

We cannot compare two pointer variables. Because variables may have random memory location. We cannot compare memory address.

char str1[10],str2[10];
char *ptr1 = str1;
char *ptr2 = str2;
if(ptr1>ptr2)  .....   // Error Here
{
....
....
}