Home »
C programming language
Pointer Rules in C programming language.
Here is the list of c programming pointer rules, these points must be remembered while you are working on pointers to avoid compilation and run time errors.
Few rules about C pointers
1) A pointer variable does not store value directly just like int, float variables. A pointer store only reference (memory address) of another variable.
Consider the following code
int x=100;
int *ptr;
ptr = &x;
Here x is a simple int variable, the current value of x is 100 while ptr is an integer pointer; the current value of ptr is the reference (memory address) of variable x.
2) A pointer variable must be initialized by a valid memory reference (memory address).
int x;
int *ptr; //pointer variable declaration
ptr = &x; //initialization with address of x
3) Do not write any dereferencing operation before initializing pointer variable with a valid memory address; this may cause run time error.
Consider the following code snippet
int x;
int *ptr;
*ptr=100; //assigning value
ptr = &x; //initializing the pointer
This code snippet is wrong; may cause run time error, because *ptr=100; is before the initialization of the pointer.
Here is the right code
int x;
int *ptr;
ptr = &x; //initializing the pointer
*ptr=100; //assigning value
4) If you do not want to assign any memory address to the pointer variable, you can define pointer as "point to nothing" by assigning NULL to that pointer.
Here NULL is a special pointer which will define pointer is not pointing to anything. But it may cause run time error so be careful while doing this.
int *ptr=NULL;
5) If you want to initialize two pointers with same memory address (reference), you can make assignment operation (=) to them.
int x=100;
int *ptr1=&x;
int *ptr2;
ptr2=ptr1;
Here pointer ptr1 and ptr2 will point to same reference (memory address of variable x)