Tuesday, November 6, 2007

Programming Language C-Tutorial4

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:

#include

#define MAX 10

int main()
{
int a[MAX], b[MAX], i;
for(i = 0; i < MAX; i++) {
a[i] = i;
b = a;
}
return(0);
}


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:

for(i = 0; i < MAX; i++) {
a[i] = i;
b[i] = a[i];
}


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[0] and b[0]. Therefore a = b; is illegal.

#include

#define MAX 10

int main()
{
int a[MAX], b[MAX], i, *p;
for(i = 0; i < MAX; i++) {
a[i] = i;
p = a;
}
return(0);
}


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.

p = a;
/* IS THE SAME AS */
p = &a[0];


Remember, a is a pointer, it points to address of the first element in the array, and always points there. &a[0]; 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:

#include

#define MAX 5

int main()
{
int a[MAX], i, *p;
a[0] = 5;
a[2] = 7;
p = a;
printf("pointer is pointing to the value %dn", *p);
p = p + 2;
printf("pointer is now pointing to the value %d", *p);
return 0;
}


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: