HOME C HOME



tally erp9 training

C, C++

POINTERS

POINTERS


INTRODUCTION:

Pointer in ‘C’ offers the flexibility in programming. It reduces the length and complexity of a program, increase the execution speed and use of a pointer array to character strings results in saving of memory space in memory. Prior to understanding the importance of pointers briefly in C, we should know about the organization of memory in computers.

Memory is organized as a sequence of byte-sized locations. These bytes are numbered beginning with a zero. The number associated with a byte is known as its address or memory location. A pointer is an entity, which contains a memory address. Thus, a pointer is a number, which specifies a location in memory. The key concepts and terminology associated with memory organization are listed below.

• Each byte in memory is associated with a unique address. An address is an integer having fixed number of bits, labeling a byte in the memory.
• Addresses are positive integer values that range from zero to the maximum size of memory.
• Every object is loaded into memory is associated with a valid range of addresses, that is, each variable and each function in a program starts at a particular location, and spans across consecutive addresses from the point onwards depending upon the size of the data item.
• The size of the data type referenced by the pointer is the number of bytes that may be accessed directly by using that address.

Consider the following declaration statement:
int rate = 250;

This statement instructs the system to find a location for the integer variable rate and stores the value 250 in to that location. Assume that the system has selected the address location 8010 for rate. We can represents this as follows:


 rate  <-------------   variable
 250   <-------------   value
 8010 <-------------   address

When executing the program, the system always associates the name rate with the address 8010. We can access the value 250 by using either the name rate or the address 8010. Since memory addresses are simply numbers, they can be assigned to some variable, which can be stored in memory, like other variables. Such variables that hold memory addresses are
called pointers. A pointer is, therefore, nothing but a variable that contains an address which is a location of another variable in memory.

Since, a pointer is a variable; its value is also stored in the memory in another location. Suppose, we assign the address of rate to the variable ptr. The link between the variable ptr and rate can be visualized as shown in fig. The address of ptr may be 9158. So the value of the variable ptr is the address of the variable rate, we may access the value of rate by using the value of ptr and therefore, we say that the variable ‘ptr’ points to the variable rate. Thus, ptr get the name “pointer”.

Variable Value Address
rate 250 8010
  Ó  
ptr 8010 9158

 
ADDRESS OPERATOR (&):

The location of variable in memory is system dependent, so user does not know the address of a variable immediately. To determine the address of variable use the address operator ‘&’. We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable, returns the address of the variable associated with it.

For example, If we give a print statement as
     printf(“%d”, &rate);

then, it prints the corresponding address of variable rate.

/*  EX-42: ILLUSTRATING THE USE OF ADDRESS OPERATOR '&'  */
main()
{
int p=75;
float q=14.10;
char ch='B';
clrscr();
printf("\n\t %d is stored at address %u",p,&p);
printf("\n\t %f is stored at address %u",q,&q);
printf("\n\t %c is stored at address %u",ch,&ch);
getch();
}
 
 


DE-REFERENCING POINTERS:

De-referencing is an operation performed to access and manipulate data contained in the memory location pointed to by a pointer. The operator * is used to de-reference pointers. A pointer variable is de-referenced when the unary operator *, in this case called the indirection operator, is used as a prefix to the pointer variable or pointer expression. Any operation performed on the de-referenced pointer directly affects the value of the variable it points to.


/*         EX-43: ILLUSTRATES DEREFERENCING OF POINTER */
main()
{
int *p,x,y; /* Declaration of pointer variable and ordinary variable */
p=&x; /* Initializing pointer p */
*p=5; /* Dereferencing p,x = 5 */
*p+=10;
clrscr();
printf("\n\tVariable x = %i\n",x);
y=*p;
printf("\n\tVariable y = %i\n",y);
p=&y;
*p+=15;
printf("\n\tNow the Variable y = %i",y);
getch();
 
OUPTUT:
Variable x=15
Variable y=15
Variable z=30 

Note:
1. The asterisk (*) used as an indirection operator has a different meaning from the asterisk used to declare pointer variables.
     int *p;

2. Indirection allows the contents of a variable be accessed and manipulated without using the name of the variable. All variables that can be accessed directly by their names, indirectly by means pointers. The power of pointers becomes evident in situations where indirect access is the only way to access variables in memory.

/*  EX-44: POINTER VARIABLE THAT CONTAINS AN ADDRESS OF ANOTHER VARIABLE  */
main()
{
int i=20;
int *j;
int **k;
j=&i;
k=&j;
clrscr();
printf("\n\t%d \t%d \t%d \t%d",i,*(&i),*j,**k);
printf("\n\t%d \t%d \t%d", j,*(&j),*k);
printf("\n\t%d \t%d",k,*(&k));
getch();
}
 
 


POINTER ARITHMETIC: The ‘C’ language allows arithmetic operations to be performed variables. It is, however, the responsibility of the programmer to see that the result obtained by performing pointer arithmetic is the address of relevant and meaningful data.

* Unary Operator : ++ (increment) and -- (decrement)
* Binary Operator: + (addition) and – (subtraction)

                                           /* EX-45: ILLUSTRATING ARITHMETIC OPERATION USING POINTERS */
main()
{
int a,b,c;
int *pa,*pb;
clrscr();
printf("\n Enter any two numbers: \n");
scanf("%d %d",&a,&b);
pa=&a;
pb=&b;
c=*pa + *pb;
printf("\n Sum of %d and %d = %d", *pa,*pb,c);
getch();
}
 
 
 

POINTERS AND FUNCTIONS:

Note:
Once again refer the call by value and call by reference, illustrated in previous chapter (functions).

POINTERS AND ARRAY:
Using a pointer can efficiently access the elements of an array. The following program illustrates the relation between pointers and arrays.

                                                   /* EX-46: POINTER AND ARRAY */
main()
{
 int iarray[5] = {1,2,3,4,5};
int i,*ptr;
ptr=&iarray[0];
clrscr();
for(i=0;i<5;i++)
{
printf("%d",ptr);
printf("\n%d",*ptr);
ptr++;
/* Increment the pointer to point to point to the next element and not to the next memory location */
}
getch();
}

 
 

In the above program, an integer array of size 5 is declared and initialized. Then, the address of the 0th element of the array is assigned to the integer pointer ptr. Within the loop, the address of the array elements is stored in ptr, and the contents of the memory location pointed to by ptr are printed. When ptr is incremented, the value stored in ptr is incremented by 2 to point to the element of the array (each integer occupies 2 bytes of memory).
 
/* EX-47: TO FIND SUM OF 7 NUMBERS USING POINTER AND ARRAY */
main()
{
int a[7],i,*ptr,s=0;
rscr();
printf("\n Enter any seven numbers: \n");
for(i=0;i<7;i++)
scanf("%d",&a[i])
ptr=&a[0];
clrscr();
for(i=0;i<7;i++,ptr++)
{
printf("\n\t%d",*ptr);
s+=*ptr;
}
printf("\n Sum of above numbers = %d",s);
getch();
}

 
 

POINTERS, ARRAYS AND FUNCTIONS:
We can use pointers in an array and functions. The following program illustrates that.

                         /* EX-48: ILLUSTRATING POINTER, ARRAY AND FUNCTION */
 #include
main()
{
void display(int *);
int no[5],*ptr,i;
clrscr();
printf("\n Enter any 10 integers:\n");
for(i=0;i<5;i++)
scanf("%d",&no[i]);
ptr=&no[0];
display(ptr);
getch();
}
void display(int *p)
{
int i;
printf("\n\t The number you have entered:");
for(i=0;i<5;i++,p++)
printf("\n\t\t%d",*p)
}
 
 

POINTERS AND STRINGS:
Pointers are widely used in handling some of the standard string library functions include strlen(), strcat(), strcpy() and strcmp(). A pointer to the string is passed to these functions instead of the entire string. A pointer thus defined can be assigned the address of an existing string, or allocated memory space, and then assigned the pointer returned by the allocation.

/* EX-49: ILLUSTRATING POINTERS AND STRINGS - TO PRINT CHAR. BY CHAR. */
 main()
{
char str[30],*ptr;
clrscr();
printf("\n Enter a string : ");
gets(str);
ptr=str;
while(*ptr!='\0')
{
printf("\n\t%c",*ptr);
ptr++;
}
getch();
}
INPUT : MEENA
OUTPUT: M
E
E
N
A


/* EX-50: PGM TO ACCEPT A STRING AND CHECK WHETHER IT IS A PALINDROME OR NOT USING POINTERS*/
 main()
{
char str[30];
char *p1,*p2;
int flag=0;
clrscr();
printf("\n Enter a string: ");
gets(str);
p2=str;
while(*p2)
p2++;
p2--;
p1=str;
while(*p1)
{
if(*p1 == *p2)
{
p1++;
p2--;
}
else
{
flag=1;
break;
}
}
if(flag==0)
printf("\n\t Yes Palindrom");
else printf("\n\t Not a Palindrom");
getch();

 
 

strcpy():
This function copies the contents of one string to another. It takes two arguments, the first being the pointer to the beginning of the destination string and the second is a pointer to the first element of the source string. The source string is copied into the destination string.

/* EX-51: PGM ILLUSTRATES STRCPY USING STD. LIB. FN AND USER DEFINED FUNCTION */
#include<string.h>
void udf(char *);
main()
{
/* int len;*/
char s1[]="SHANKAR";
char s2[50],*p;
strcpy(s2,s1);
clrscr();
printf("\n\n\t Copied string using standard library function: %s",s2);
udf(s1);
}

void udf(char* s1)
{
int i=0;
char name2[20],*ptr;
ptr=&s1[20];
i=0;
while(s1[i]!='\0')
{
name2[i]=s1[i];
ptr++;
i++;
}
name2[i]='\0';
printf("\n\t Copied string using user defined function: %s",name2);
getch();
}
 
 

The function udf can be reduced by using while (*p++ = *q++); the expression *p++ will evaluate p++. The ++ operator is evaluated first, since unary operator associates right to left. The pointer is now de-referenced. The pointer p, is then incremented. Similar operations are done on q. The character pointed to by q is assigned to that pointed to that pointed to by p. The while loop continues till the NULL pointer is encountered.

strchr():
The function strchr() searches for a character in a string. It accepts two parameters. The first one is a string, while the second one is a character. The function searches for a specified character in the string passed and returns the memory address of the first matching symbol character found in the string. For example consider the following program.

/* EX-52: PGM TO FIND POSITION OF A CHARACTER IN GIVEN STRING */
#include<stdio.h>
#include<string.h>
main()
{
char string[30];
char findchar;
char *found;
printf("Input a string: ");
/* scanf("%s",string); */
gets(string);
fflush(stdin);
printf("Input a character: ");
scanf("%c",&findchar);
found=strchr(string,findchar);
printf("%c was found in position %d",findchar,found-string);
getch();
}
 
SAMPLE RUN 1: Input a String: Baskaran Input a character: k k was found in position 3
SAMPLE RUN 2: Input a String: Rathinavel Input a character: R R was found in position 0

Note: Array subscripts in ‘C’ always begin with a zero. But what happen if the character is not found in the given string? The function returns a NULL pointer, which is a memory address having the value zero.