Pointers and Arrays
Arrays and pointers are closely linked in C. To use arrays effectively it's a good idea to know how to use pointers with them. Let's have a look at an example:
Compile this program and run it.It won't run, why? Because you can't assign a to b. You have to use something like this:
The line #define MAX 10 is a simple constant. We haven't seen this before so i should mention it. All it is in a CONSTANT value we can use throughout the program. MAX is a variable that holds the value of 10, only we cannot modify it, it's constant. Constants are normally typed in upper-case to make it obvious to anyone reading the program that it is a constant.
a and b are unusual in C in that they're not techinically arrays themselves. They are permanent pointers. What does that mean? Well, a POINTS to the first item in its array, and b POINTS to the first item in it's array, they are pointers, only they cannot be changed to point to something else. They hold the addresses of a and b. Therefore a = b; is illegal.
The code above is legal. p = a; works because a is techically a pointer, so assigning a to p makes p contain the address of the first element of of the array a. So now *p points to a.
Remember, a is a pointer, it points to address of the first element in the array, and always points there. &a; is the address of the same item in the array, so they are the same.
Now that we have assigned the address of a's first element to p, we can use the pointer to move around the array, consider the below:
This will output:pointer is pointing to the value 5
pointer is now pointing to the value 7
Do you see? We can use the pointer to jump through the array elements. If we increment p then the pointer will jump the appropriate number of bytes to the next array item. C takes care of the issue of element size, so adding one will jump to the next element, adding two will jump to the element after the next element... etc.
No Comments for this page.