You are on page 1of 2

COMMON POINTER MISTAKES WHILE PROGRAMMING

We all know that pointer is used to store the address of a variable.


Pointer Variable stores the address of variable.
Below are some of the common mistakes committed by Novice programmer.

Pointer Mistake 1: Assigning Value to Pointer Variable

int * ptr , m = 100 ;


ptr = m ;

// Error on This Line

Correction:
1. ptr is pointer variable which is used to store the address of the
variable.
2. Pointer Variable ptr contain the address of the variable of type
int as we have declared pointer variable with data type int.
3. We are assigning value of Variable to the Pointer variable, instead
of Address.
4. In order to resolve this problem
variable to pointer variable

we

should

assign

address

of

Write it like this

ptr = &m ;

Pointer Mistake 2: Assigning Value to Uninitialized Pointer


We are assigning the value to the pointer variable. We all know that
pointer is special kind of variable which is used to store the address
of another variable. So we can store only address of the variable to the
pointer variable.

int * ptr , m = 100 ;


*ptr = m ;
// Error on This Line
We are going to update the value stored at address
uninitialized pointer variable. Instead write it as

int * ptr , m = 100 ,n = 20;


ptr = &n;
*ptr = m ;

pointed

by

Firstly initialize pointer by assigning the address of integer


Pointer variable. After initializing pointer we can update value.

to

Pointer Mistake 3: 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);
In the above example, You will not get any compiler or run time error
but it is considered as common mistake by novice user to de-reference
pointer variable without using asterisk (*)

Pointer Mistake 4: Assigning Address of Un-initialized Variable

int *ptr,m;
ptr = &m;
Best practice while using pointer is to initialize pointer before using
it.
We can assign any valid address to pointer variable but if you assign
the address of un-initialized variable to pointer then it will print
garbage value while de-referencing it.

Pointer Mistake 5: 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

You might also like