Jan 7, 2008

A C pointer FAQ ( kind of ) [ as of now for me ]

Of course, pointers are not limited to ints. It's quite common to use pointers to other types, especially char. Here is the innards of the mystrcmp function we saw in a previous chapter, rewritten to use pointers. (mystrcmp, you may recall, compares two strings, character by character.)

 // p1, p2 point to the address of the first character in str1, str2 respectively
 char *p1 = &str1[0], *p2 = &str2[0];

 while(1)
  {
   // compare the values of str1[x], str[x] at the position x. Not equal
   if(*p1 != *p2)
    return *p1 - *p2;
   // we reached the end of both str1, str2 -> they are equal.
   if(*p1 == '\0' || *p2 == '\0')
    return 0;
   // p1++ and p2++ do the increment of p1 and p2.
   // i.e., the next characters in str1 ( str[x + 1] and str2 ( str2[ x + 1]
   p1++;
   p2++;
  }


As another example, here is the strcpy (string copy) loop from a previous chapter, rewritten to use pointers:

 char *dp = &dest[0], *sp = &src[0];
 while(*sp != '\0')
  // *dp++ means *(dp++), i.e., the value of the pointer next to dp.
  // to access the address of the next pointer of dp, use (*dp)++
  *dp++ = *sp++;
 *dp = '\0';

(One question that comes up is whether the expression *dp++ increments p or what it points to. The answer is that it increments p. To increment what p points to, you can use (*dp)++.) 

ref: http://www.eskimo.com/~scs/cclass/notes/sx10b.html

3 comments:

Anonymous said...

If you are like me and love garlic, you are
already too late. In addition, fertilizer restores to the
soil nutrients that are absorbed by years of growing
the same vegetable plants in the same location. Each has
his own concoction of soapy water, tobacco juice or hot pepper
solutions to to deter these nasty pests and try those first.


my site: satyr

Anonymous said...

Otherwise you may feel frustration to play these games.
Nowadays with flight simulators you can have lots of fun out of these games and besides all this you
do not have to spend thousands. The students are imparted cost-effective training into experiencing and learning how situations of emergency can be handled.
We would like to invite you to join our virtual airline in Ireland
if you have some time that you can spend with is
to fly online. Unfortunately, the series has been dormant for quite some time and there isn't any indication that it will be returning anytime soon.

Stop by my blog ... simulator

Anonymous said...

With a 60 day maturity, turnips need to be in the ground by August 15.

Wear disposable gloves to keep from directly touching feces.

The less competition, the better off your plants will be.


my web blog; mulching