Next: Arrays of Pointers Up: Pointers Previous: Pointer and Functions

Pointers and Arrays

Pointers and arrays are very closely linked in C.

Hint: think of array elements arranged in consecutive memory locations.

Consider the following:

Fig. Arrays and Pointers

To get somewhere in the array (Fig. ) using a pointer we could do:

pa + i a[i]

WARNING: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things.

C however is much more subtle in its link between arrays and pointers.

For example we can just type

pa = a;

instead of

pa = &a[0]

and

a[i] can be written as *(a + i). i.e. &a[i] a + i.

We also express pointer addressing like this:

pa[i] *(pa + i).

However pointers and arrays are different:

This stuff is very important. Make sure you understand it. We will see a lot more of this.

We can now understand how arrays are passed to functions.

When an array is passed to a function what is actually passed is its initial elements location in memory.

So:

strlen(s) strlen(&s[0])

This is why we declare the function:

~int strlen(char s[]);

An equivalent declaration is : int strlen(char *s); since char s[] char *s.

strlen() is a standard library function (Appendix ) that returns the length of a string. Let's look at how we may write a function:

Now lets write a function to copy a string to another string. strcpy() is a standard library function that does this.

This uses pointers and assignment by value.

Very Neat!!

NOTE: Uses of Null statements with while.


Dave.Marshall@cm.cf.ac.uk
Wed Sep 14 10:06:31 BST 1994