10 Pointers
10 Pointers
10 Pointers
● General form:
type-name *variable-name;
int *p;
● Declaration sets aside space for a pointer, doesn’t make it point to an object
● Crucial to initialize before using
int i, *p;
…
p = &i;
● Can initialize a pointer variable when declared, also it can be combined
int i;
int *p = &i;
int j, *q = &j;
The Address and Indirection Operators
The Indirection Operator
i = 1;
int *p;
printf("%d", *p); /*** WRONG ***/
int *p;
*p = 1; /*** WRONG ***/
Pointer Assignment
● C allows the use of the assignment operator to copy pointers of same type
● Assume that the following declaration is in effect:
int i, j, *p, *q;
p = &i;
● Another example of pointer assignment:
q = p;
q now points to the same place as p:
● Can change i using either *p or *q
Pointer Assignment
● Do not confuse q = p; (Pointer Assignment) with *q = *p;
p = &i;
q = &j;
i = 1;
*q = *p;
Pointers as Arguments
● Can be used to modify arguments:
void decompose(double x, long *int_part, double *frac_part){
*int_part = (long) x;
*frac_part = x - *int_part;
}
● Possible prototypes:
void decompose(double x, long *int_part, double *frac_part);
void decompose(double, long *, double *);
Pointers as Arguments
● A call of decompose:
decompose(3.14159, &i, &d);
Pointers as Arguments
● Arguments in calls of scanf
int i;
scanf("%d", &i);
without &, scanf only gets the value of i
● Don’t use & with pointers ⇒ scanf("%d", &p); /*** WRONG ***/
Pointers as Arguments
● Failing to pass a pointer to a function when one is expected can have
disastrous results
● A call of decompose in which the & operator is missing:
decompose(3.14159, i, d);
● The max_min.c program uses a function named max_min to find the largest
and smallest elements in an array
● Prototype for max_min:
● When max_min finds the largest element in b, it stores the value in big by
assigning it to *max
return &a[n/2];