Lec 22 PointersInFunction
Lec 22 PointersInFunction
Autumn 2020
Pointers in
Function
Passing Pointers to a Function
float average (int a, float x[]) float average (int a, float *x)
{ {
: :
sum = sum + x[i]; sum = sum + x[i];
} }
p = array;
Right
#define ARRAY_SIZE 10
int i, a[ARRAY_SIZE];
for(i = 0; i < ARRAY_SIZE; i++){ ... }
} }
Arrays and pointers
int a[20], i, *p;
Use pointers
Return one value as usual with a return statement
void add(struct cplx *x, struct cplx *y, struct cplx *t)
{
t->re = x->re + y->re;
struct cplx { t->im = x->im + y->im;
}
float re;
float im;
};
int main()
{
struct cplx a, b, c;
scanf(“%f%f”, &a.re, &a.im);
scanf(“%f%f”, &b.re, &b.im);
add(&a, &b, &c) ;
printf(“\n %f %f”, c.re, c.im);
return 0;
}
Remember: The Actual Mechanism
Changes made inside the function are thus also reflected in the
calling program.
Typecasting
void pointers
Pointers defined to be of specific data type cannot hold
the address of another type of variable.
int num=100;
void *p;
p=π
printf(“First p points to a float variable and access pi=%.5f\n", *((float *)p));
p=#
printf("Then p points to an integer variable and access num=%d\n",*((int *)p));
return 0;
}
Pointers to Pointers
Pointer is a type of data in C
hence we can also have pointers to pointers
General format:
<data_type> **<ptr_to_ptr>;
<ptr_to_ptr> is a pointer to a pointer pointing to a data object of
the type <data_type>