Friday, July 29, 2016

C Basics - Pointers in C

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
The general form of a pointer variable declaration is −

type *var-name;

Example:

int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *cp     /* pointer to a character */

Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. The unary operator * that returns the value of the variable located at the address specified by its operand.

#include <stdio.h>

int main () {

   int  a;   
   int  *b;        

   b = &a;  /* store address of a in b*/

   printf("Address of a is: 0x%x\n", &a  );   
   printf("Address stored in b is: 0x%0x\n", b );
 
 a = 5;    
   printf("Value of *b variable is: %d\n", *b );

   return 0;
}
The output of the above program would be:

Address of a is: 0x28ff38
Address stored in b is: 0x28ff38
Value of *b variable is: 5

A pointer that is assigned NULL is called a null pointer.The NULL pointer is a constant with a value of zero defined in several standard libraries.

#include <stdio.h>

int main () {

   int  *a = NULL;   

   printf("Address stored in a is: 0x%0x\n", a );

   return 0;
}
The output of the above program would be:

Address stored in a is: 0x0

Programmer must check the pointer before accessing the value in it.

#include <stdio.h>

int main () {

   int  *a = NULL;   
   int  b = 5;

   printf("Address stored in a is: 0x%0x\n", a );
   if(a == NULL){
    a = &b;
    printf("Value of *a variable is: %d\n", *a );
   }

   return 0;
}
The output of the above program would be:

Address stored in a is: 0x0
Value of *a variable is: 5



Related topics:
Pointer Arithmetic in C   |   Pointer to an Array in C   |   Returning Array from a Function in C   |   Array of Pointers in C   |   Pointer to Pointer in C   |   Pointers and Functions in C

List of topics: C Programming

No comments:

Post a Comment