Passing Pointers

Download Report

Transcript Passing Pointers

Example 1
125
int x = 100;
sub1 (&x);
passing the address of x
void sub1 (int *pint)
{
*pint = *pint + 25;
}
x
pint
or
de-referenced value of
pint is the value of what
pint points to
pint
&x
100
Example 2
125
int x = 100;
int *p = &x;
sub1 (p);
passing the value of p
which is the address of x
void sub1 (int *pint)
{
*pint = *pint + 25;
}
de-referenced value of
pint is the value of what
pint points to
100
x
pint
p
Example 3
125
int x = 100;
int *p = &x;
sub2 (&p);
passing the address of p
void sub2 (int **ppint)
{
**ppint = **ppint + 25;
}
p
ppint
double de-referenced
value of ppint is the
value of the value of
what ppint points to
100
x
Example 4
int x = 100;
int *p = &x;
sub2 (&p);
passing the address of p
void sub2 (int **ppint)
{
*ppint = malloc(sizeof(int));
**ppint = 50;
p
ppint
}
single de-referenced
value of ppint is the
value of what ppint
points to. In this case,
we are assigning a value
to what ppint points to.
100
x
double de-referenced
value of ppint is the
value of the value of
what ppint points to
50
malloc-ed
Example 5
int x = 100;
int *p = &x;
sub2 (&p);
passing the address of p
void sub2 (int **ppint)
{
ppint = malloc(sizeof(int));
*ppint = 50;
p
ppint
}
no de-referencing !!
What is this changing?
ppint itself
100
x
single de-referenced
value of ppint is the
value of what ppint
points to
50
malloc-ed