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:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this
case) */
0 1 ………… 9
a
pa ++pa pa+i
Fig. 9.3 Arrays and Pointers
To
get somewhere in the array (Fig. 9.3) 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.
i.e. &a[i] º a + i.
We also
express pointer addressing like this:
pa[i]
º *(pa + i).
However
pointers and arrays are different:
- A pointer is a variable. We can do
pa = a and pa++. - An Array is not a variable. a = pa and a++ ARE ILLEGAL.
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.
since char s[] ºchar *s.
strlen() is a
standard library function (Chapter 18)
that returns the length of a string. Let's look at how we may write a function:
int strlen(char *s)
{ char *p = s;
while
(*p != `\0);
p++;
return
p-s;
}
Now lets
write a function to copy a string to another string. strcpy() is a standard
library function that does this.
void strcpy(char *s, char *t)
{
while ( (*s++ = *t++) != `\0);}
This uses pointers
and assignment by value.
Very Neat!! NOTE:
Uses of Null statements with while.
No comments:
Post a Comment