Saturday, 27 July 2013

Pointers in c

 A pointer is an address. Instead of  a variable, it is a pointer to a variable which is  stored somewhere in the memory of the program. Let  examine the a program [POINTER.C] which has some pointers to understand the concept of pointers.
C Programming
C Programming


#include "stdio.h"
/* illustration of pointer use */
void main( )
{
int i, *p1, *p2;
i = 39;        /* any  value */
p1 = &index;   /* the address of i */
p2 = pt1;
printf("The value is %d %d %d\n", i, *p1, *p2);

*p1 = 13; /* lets changes the value of i*/
printf("The value is %d %d %d\n", i, *p1, *p2);
}

We declare the pointers with the help of  star(asterisk).
Lets examine the first statement, it is clear that we assign 39 to the variable i. 
In next  statement, we assign the address of i to pt1."&" shows th address.
In this example, p1 and p2 are pointers, and the variable i is a simple variable.Before explaining the rest of program lets have look on Two very important s rule for using the pointers.



Two very important rules:

1. A variable have an ampersand (&) in front of it      refers to the address of the variable. line no 7. 
2.  A pointer with a star in front of it define  the value  of the variable.

 pointed to by the pointer. line no.10.

Memory aids::

1. Think of & as an address.

2. Think of * as a star referring to stored.

 As a pointers p1 and p2 do not contain a  value but an address of a variable. Line 7 in program assigns the pointer p1 to point to the variable i.


Line 10 modifies the value by using the pointer. because p1 points to the variable index, then putting a star in front of the pointer refers to the memory location to which it is pointing
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

0 comments:

Post a Comment