passing *char parameters by reference

Rick Schaut schaut at madnix.UUCP
Fri Aug 11 23:33:16 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?

[swap(x,y)]
>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);
>}

You need to declare the parameters to swap to be pointers to pointers
to chars:

swap(x,y)
char **x,**y;
{
	register char *temp;

	temp = *x;
	*x = *y;
	*y = temp;
}

Now the call, swap(&a, &b) will work correctly.  Remember, you're
passing the pointers by reference, not the arrays, hence the extra
level of indirection.

-- 
   Richard Schaut     Madison, WI              Madison: an alternative
ArpaNet: madnix!schaut at cs.wisc.edu                      to reality.
UseNet: ...uwvax!astroatc!nicmad!madnix!schaut
             {decvax!att}!



More information about the Comp.lang.c mailing list