Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Watcom C/C++ User's Guide - a self based pointer infers its segment value from itself. it is http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
A self based pointer infers its segment value from itself.  It is
particularly useful for structures such as linked lists, where all of the
list elements are in the same segment.  A self based pointer pointing to one
element may be used to access the next element, and the compiler will use
the same segment as the original pointer.

The following example illustrates a function which will print the values
stored in the last two members of a linked list:

Example:

     struct a {
         struct a __based( __self ) *next;
         int                         number;
     };



     extern void PrintLastTwo( struct a far *list )
     {
       __segment                seg;
       struct a __based( seg ) *aptr;

       seg  = FP_SEG( list );
       aptr = FP_OFF( list );
       for( ; aptr != _NULLOFF; aptr = aptr->next ) {
         if( aptr->next == _NULLOFF ) {
           printf( "Last item is %d\n",
                   aptr->number );
         } else if( aptr->next->next == _NULLOFF ) {
           printf( "Second last item is %d\n",
                   aptr->number );
         }
       }
     }

The argument to the function PrintLastTwo is a far pointer, pointing to a
linked list structure anywhere in memory.  It is assumed that all members of
a particular linked list of this type reside in the same segment of the
computer's memory.  (Another instance of the linked list might reside
entirely in a different segment.) The object seg is given the segment
portion of the far pointer.  The object aptr is given the offset portion,
and is described as being based in the segment stored in seg.

The expression aptr->next refers to the next member of the structure stored
in memory at the offset stored in aptr and the segment implied by aptr,
which is the value stored in seg.  So far, the behavior is no different than
if next had been declared as,


     struct a *next;

The expression aptr->next->next illustrates the difference of using a self
based pointer.  The first part of the expression ( aptr->next) occurs as
described above.  However, using the result to point to the next member
occurs by using the offset value found in the next member and combining it
with the segment value of the pointer used to get to that member, which is
still the segment implied by aptr, which is the value stored in seg.  If
next had not been declared using __based( __self ), then the second pointing
operation would refer to the offset value found in the next member, but with
the default data segment (DGROUP), which may or may not be the same segment
as stored in seg.

Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson