Pointer incrementation and assignment

Eric Giguere giguere at aries5.uucp
Fri May 26 14:57:49 AEST 1989


In article <2015 at csuna.csun.edu> abcscagz at csuna.csun.edu (Jeff Boeing) writes:
>Furthermore, if the compiler allows it, this is also perfectly legal:
>
>      a = 4000;
>
>This sets a to point to memory location 4000.  A subsequent a++ would increase
>a to 4002.  But would doing this:
>
>      a += 1;
>
>increase a by 1 or by 2?  Or how about
>
>      a = a + 1;

Both cases yield the same result as a++ so that a is now 4002 and not 4001.
In C it's implicit that any integer added to a pointer is first multiplied
by the size of the pointer's base type... I don't have the Standard in front
of me, but to quote K&R 2 on page 205:

   "A pointer to an object in an array and a value of any integral type
    may be added.  The latter is converted to an address offset by
    multiplying it by the size of the object to which the pointer points. 
    The sum is a pointer of the same type as the original pointer ...."

This feature can be useful when dealing with non-trivial types, such as
arrays of structures.  One of my favorite ways to display several lines
of static text is to use something of the form:

    static char *MyText[] =
      {
        "Usage:  blart [-r] problem\n",
        "    blart is a generic program suitable for general-purpose",
        "    problem solving and is often described in the literature.\n",
        "    Arguments:\n",
        "        -r       solve some problem at random",
        "        problem  a specific problem to be solved\n",
        "    See also `foo'.",
        NULL
      };

    Usage()
      {
        char **text;

        for( text = MyText; *text != NULL; ++text )
            puts( *text );
      }

Here I specifically depend upon the fact that `++text' adds   

     sizeof( char * )

to the current value of `text' to get me the next element in the array...

Eric Giguere                                  268 Phillip St #CL-46
For the curious: it's French ("jee-gair")     Waterloo, Ontario  N2L 6G9
Bitnet  : GIGUERE at WATCSG                   (519) 746-6565
Internet: giguere at aries5.UWaterloo.ca         "Nothing but urges from HELL!!"



More information about the Comp.lang.c mailing list