Pointers

Pointers


Pointers are the variable that stores the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data types such as int, float, char, double, short etc.

Instead of storing a value, a pointer will store the address of a variable.

Syntax :
datatype *var_name; 

Example :

int *ptr;  

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

  1. Normal variable stores the value whereas pointer variable stores the address of the variable.
  2. The content of the C pointer always be a whole number i.e. address.
  3. Always C pointer is initialized to null, i.e. int *p = null.
  4. The value of null pointer is 0.
  5. & symbol is used to get the address of the variable.
  6. * symbol is used to get the value of the variable that the pointer is pointing to.
  7. If a pointer in C is assigned to NULL, it means it is pointing to nothing.
  8. Two pointers can be subtracted to know how many elements are available between these two pointers.
  9. But, Pointer addition, multiplication, division are not allowed.
  10. The size of any pointer is 2 byte (for 16 bit compiler).

Example:

#include <stdio.h>
int main()
{
   int *ptr, q;
   q = 50; 
   /* address of q is assigned to ptr */
   ptr = &q;
   /* display q's value using ptr variable */
   printf("%d", *ptr);
   return 0;
}

Example 2:

# include <stdio.h> 
void fun(int *ptr) 
*ptr = 30; 

int main() 
int y = 20; 
fun(&y); 
printf("%d", y); 

return 0; 

Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&y)’, address of y is passed so that y can be modified using its address.

Comments