To declare a pointer
int *px;
Now px is an interger pointer. To make this point to some variable.
int x;
px = &x;
px will now point to the address of x (& is called the reference operator or address operator).
To get the value from that address use * (called the dereference operator)
*px = 10; /* equal to x = 10; */
Now for a single dimensional arrays.
int a[10];
int *pa;
pa = &a;
Now a[0] = *pa, a[1] = *(pa+1) and so on.
pa+1 means advance pointer to next location by 1 times the size of the pointer type.
So the above statement pa+1 means advance by pa by size of int, so now it points to a[1] after a[0].
Try a simple exercise now to do this.
1. Use only pointers to get the sum of all elements in an array
2. Binary search using pointers.
Once we are clear with the pointer concepts
~Maddy
No comments:
Post a Comment