Explain Pointers and Arrays with example
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) */
Fig. Arrays and Pointers
To get somewhere in the array as in above 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:
• 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.
strlen() is a standard library function 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.