passing *char parameters by reference

Sun Visualization Products matthew at sunpix.UUCP
Fri Aug 11 00:56:50 AEST 1989


In article <1424 at novavax.UUCP>, gls at novavax.UUCP (Gary Schaps) writes:
| Would someone be kind enough to tell me why this program fails?
| 
| char *x, *y;
| {
|    register char *temp;
| 
|    temp = x;
|    x = y;
|    y = temp;
| }
| 
| main()
| {
|    char *a="aaaa";
|    char *b="bbbb";
| 
|    swap( &a, &b );
|    printf( " a = %s\t b = %s\n", a, b);
| }


Sure!!  

First off you have two functions, but only one has a name. Since 'main()' 
calls a function 'swap()', and the un-named function looks like a swap 
function, You need to prefix the function with a:

	swap( x, y )



Secondly, and where your biggest problem is, is in the swapping of pointers.

1) main correctly passes the address of the pointers a and b to the 
   swap() funtions. (or in other words main is passing "pointers to 
   pointer" to swap().

2) The swap() function is then swapping the pointers to pointers around. 
   The effect 'pointer x is now pointing to pointer b', and 'pointer y 
   is now pointing to pointer a'.  The values of pointers a and b have 
   not been swapped, just the pointers to the pointers.  I.E.:

     x -> a -> "aaaa"    becomes     y -> a -> "aaaa"
     y -> b -> "bbbb"    becomes     x -> b -> "bbbb"

    (Notice: the relationship between a and "aaaa" and b and "bbbb" do not
     change).


Solution: Add another level of indirection to swap.  Make the variables
    x and y into pointer to pointers (i.e.: **x and **y) then swap the
    contents of the whats being pointed to by x (*x) with the contents
    of whats being pointed to by y (*y).  Below is a correct swap routine.
    (Notice: Since no mathimatical operations are being done on these
     pointers to pointers, I've taken the liberty of converting them
     to type 'void', since pointer type is only important when doing
     mathimatical operations on the pointers themselves.)


          
          void swap(x,y)          /* Per K&R edition 1, page 117 */
          void **x, **y;          /* Substituted **x for *x[]    */
          {
             register void *temp;
          
             temp = *x;
             *x = *y;
             *y = temp;
          }


  (Authors note: Code tested on a Sun 3/50 workstation running SunOS 4.0.1)


-- 
Matthew Lee Stier                            |
Sun Microsystems ---  RTP, NC  27709-3447    |     "Wisconsin   Escapee"
uucp:  sun!mstier or mcnc!rti!sunpix!matthew |
phone: (919) 469-8300 fax: (919) 460-8355    |



More information about the Comp.lang.c mailing list