Sunday, September 26, 2010

Pointer Comparisons in C,C++

You can compare two pointers in a relational expression. For instance, given two
pointers p and q, the following statement is perfectly valid:
if(p<q) printf("p points to lower memory than q\n");
Generally, pointer comparisons are used when two or more pointers point to
a common object, such as an array. As an example, a pair of stack routines are
developed that store and retrieve integer values. A stack is a list that uses first-in,
last-out accessing. It is often compared to a stack of plates on a table—the first
one set down is the last one to be used. Stacks are used frequently in compilers,
interpreters, spreadsheets, and other system-related software. To create a stack,
you need two functions: push() and pop() . The push() function places values on
the stack and pop() takes them off. These routines are shown here with a simple
main() function to drive them. The program puts the values you enter into the
stack. If you enter 0, a value is popped from the stack. To stop the program,
enter −1.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
void push(int i);
int pop(void);
int *tos, *p1, stack[SIZE];
int main(void)
{
int value;
tos = stack; /* tos points to the top of stack */
p1 = stack; /* initialize p1 */
do {
printf("Enter value: ");
scanf("%d", &value);
if(value!=0) push(value);
else printf("value on top is %d\n", pop());
} while(value!=-1);

return 0;
}
void push(int i)
{
p1++;
if(p1==(tos+SIZE)) {
printf("Stack Overflow.\n");
exit(1);
}
*p1 = i;
}
int pop(void)
{
if(p1==tos) {
printf("Stack Underflow.\n");
exit(1);
}
p1--;
return *(p1+1);
}
You can see that memory for the stack is provided by the array stack. The pointer
p1 is set to point to the first element in stack. The p1 variable accesses the stack. The
variable tos holds the memory address of the top of the stack. It is used to prevent
stack overflows and underflows. Once the stack has been initialized, push() and
pop() may be used. Both the push() and pop() functions perform a relational test
on the pointer p1 to detect limit errors. In push() , p1 is tested against the end of
stack by adding SIZE (the size of the stack) to tos. This prevents an overflow. In
pop() , p1 is checked against tos to be sure that a stack underflow has not occurred.
In pop() , the parentheses are necessary in the return statement. Without them, the
statement would look like this:
return *p1 +1;
which would return the value at location p1 plus one, not the value of the location p1+1.

No comments:

Post a Comment