Académique Documents
Professionnel Documents
Culture Documents
Pointer Variables
p = &x;
x ? p Value of p has
been changed
*p = 4;
x 4 p Value of x has
been changed
The Null Pointer
NULL .
Pointer Example
int *p, x, y, *q = NULL;
p = &x;
*p = 4;
p x 4 y ? q .
(or *p)
p = &y;
p x 4 y ? q .
p x 4 y 8 . q
*p
q = p;
p x 4 y 8 q
*p or *q
p = &x;
p x 4 y 8 q
*p *q
*p = *q;
p x 8 y 8 q
*q
*p
8
Arrays of Pointers
int j = 6; k = 4;
Pointers in array are
int * arrayOfPtr[4]; not initialized yet
6 j 4 k ? ? ? ?
arrayOfPtr 0 1 2 3
arrayOfPtr[0] = &k;
arrayOfPtr[2]=&j;
6 4
? ?
j k arrayOfPtr 0 1 2 3
Array Names as Pointers
void* ptr;
• Any kind of pointer can be stored in a variable
whose type is void*
• If we know that a value in a pointer p of type
void* is really of a specific pointer type x, and
we want to treat the value p points to as a
value of type x, we have to cast the pointer to
type x
Generic Pointer Example
void * arr[6];
int j = 7;
double k = 5.9;
x ? k 5.9 int * n;
double x;
n ? j 7
arr ? ? ? ? ? ?
0 1 2 3 4 5
arr[2] = (void*)&j; /*cast is okay, but not
needed here */
x ? k 5.9
n ? j 7
arr ? ? ? ? ?
0 1 2 3 4 5
arr[5] = &k; /* cast not needed, but
could be used */
x ? k 5.9
n ? j 7
arr ? ? ? ?
0 1 2 3 4 5
n = (int*)arr[2]; /* cast is required here */
x ? k 5.9
n 7
j
arr ? ? ? ?
0 1 2 3 4 5
x = *((double*)arr[5]); /* cast is required here */
x 5.9 k 5.9
n 7
j
arr
? ? ? ?
0 1 2 3 4 5
Created By,