Pointers and Arrays

There is a very close relationship between pointer and array notation in C. As we have seen already the name of an array ( or string ) is actually the address in memory of the array and so it is essentially a constant pointer.
 Example

char str[80], *ptr ;
ptr = str ;/* causes ptr to point to start of string str */
ptr = &str[0] ; /* this performs the same as above */
It is illegal however to do the following
str = ptr ; /* illegal */
as str is a constant pointer and so its value i.e. the address it holds cannot be changed.
Instead of using the normal method of accessing array elements using an index we can
use pointers in much the same way to access them as follows.
char str[80], *ptr , ch;
ptr = str ; // position the pointer appropriately
*ptr = 'a' ; // access first element i.e. str[0]
ch = *( ptr + 1 ) ; // access second element i.e. str[1]
Thus *( array + index ) is equivalent to array[index].
Note that the parentheses are necessary above as the precedence of * is higher than that of +. The expression
ch = *ptr + 1 ;

for example says to access the character pointed to by ptr ( str[0] in above example with value ‘a’) and to add the value 1 to it. This causes the ASCII value of ‘a’ to be incremented by 1 so that the value assigned to the variable ch is ‘b’.
In fact so close is the relationship between the two forms that we can do the following
int x[10], *ptr ;
ptr = x ;
ptr[4] = 10 ; /* accesses element 5 of array by indexing a pointer */
Pointers and Arrays Pointers and Arrays Reviewed by Unknown on 04:41 Rating: 5

No comments:

Powered by Blogger.