Credits

Sunday, March 1, 2009

More Pointer Lectures

Reasons why pointers must be well understood:

1. Pointers provide the means by which functions can modify their calling arguments.
2. Pointers are used to support TC's dynamic allocation system.
3. The use of pointers can improve the efficiency of certain routines.
4. Pointers are commonly used to support certain data structures such as linked lists and binary trees.

Dangers of Pointer, however should not be ignored:

1. Uninitialized or wild pointers can cause the system to crash
2. Too many pointers may be difficult to trace or debug.

Check these sample programs that show wrong use of pointers.



[+/-] show/hide





#include stdio.h /*enclose this in <> */
main()
{
float x,y;
int *p;
x=123.45;
p=&x;
y=*p;
printf("%f",y); /* this is wrong since pointers only work on integers */
getch();
}

/*Another sample program*/
#include stdio.h /*enclose this in <> */
main()
{
int x,*p;
x=10;
*p=x; /* x is assigned to unknown memory address */
printf("%d",p);
getch();
}

/*Another sample program*/
#include stdio.h /*enclose this in <> */
main()
{
int x,*p;
x=10;
p=x;
printf("%d",*p); /* p does not hold 10, to correct this, add & to x*/
getch();
}

Output of all these codes: Runtime Error

AddThis