Pointer arithmetic
- In addition to single variables, pointers can be used to access parts of an
array.
int *ip;
int a[20];
ip = &a[3];
Given that ip points to element 3 of a, we can use pointer
arithmetic to access elements before or after 3, as in
ip++;
*ip = 7;
*(ip+1) = 8;
*(ip-2) = 3;
which sets element 4 to 7, element 5 to 8 and element 2 to 3.
*MUST* remember the type (and the size of the type) when doing pointer arithmeti
c.
String operations using pointers
- mystrcmp() using pointers
char *p1 = &str1[0], *p2 = &str2[0];
while(1) {
if (*p1 != *p2)
return *p1 - *p2;
if (*p1 == '\0')
return 0;
p1++;
p2++;
}
mystrcpy() using pointers
char *dp = &dest[0], *sp = &src[0];
while (*sp != '\0')
*dp++ = *sp++;
*dp = '\0';