Pointer
Pointer
Variable
ADDR16 Contents16
Lect 14 P. 8
Pointer Variable
Assume ptr is a pointer variable and x is an integer variable
x 10
ptr &x
int main()
{
int x;
int *ptr;
x = 10;
ptr = &x;
*ptr = *ptr + 1;
cout<< x;
return 0;
Pointer arithmetic
Valid operations on pointers include:
- the sum of a pointer and an integer
- the difference of a pointer and an integer
- pointer comparison
-the difference of two pointers.
-Increment/decrement in pointers
- assignment operator used in pointers
Example
void main()
{
int a=25,b=78,sum;
int *x,*y;
x=&a;
y=&b;
sum= *x + *y;
cout<<“Sum is : ”<<sum;
}
Assignment in pointers
• int main()
• {
• Int x, *p1, **p2;
• x=100;
• p1=&x;
• P2=&p1;
• cout<<**p2;
• }
Void pointers
• When a variable is declared as being a pointer to
type void it is known as a generic pointer.
• Since you cannot have a variable of type void, the
pointer will not point to any data and therefore
cannot be dereferenced.
• It is still a pointer though, to use it you just have to
typecast it to another kind of pointer first. Hence the
term Generic pointer.
• This is very useful when you want a pointer to point
to data of different types at different times.
• Syntax:
void * variable name;
void main()
{ int i;
char c;
void *data;
i = 6;
c = 'a';
data = &i;
cout<<"the_data points to the integer value “<< *(int*) data;
data = &c;
cout<<"the_data now points to the character “<< *(char*) data;
}
• PROBLEMS WITH POINTERS
DANGLING POINTER
int * p;
• p = 0; // p has a null pointer value
•
Do not confuse null pointers with void pointers. A null pointer is a value
that any pointer may take to represent that it is pointing to "nowhere",
while a void pointer is a special type of pointer that can point to
somewhere without a specific type. One refers to the value stored in
the pointer itself and the other to the type of data it points to.
WILD POINTER