C語言:兩數交換 (Swap in C)

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

#include<stdio.h>
#include<stdlib.h>

voidswap( void*a, void*b, size_t size );

intmain(void)
{
  doublehi = 12.345, good = 543.21;

  printf( "hi = %lf\tgood = %lf\n", hi, good );
  swap( &hi, &good, sizeof(double) );
  printf( "hi = %lf\tgood = %lf\n", hi, good );
  return0;
}

// byte-by-byte swap
voidswap( void*a, void*b, size_t size )
{
  size_t i;
  char*p = (char*)a;
  char*q = (char*)b;

  chartemp;
  for( i = 0; i < size; i++, p++, q++ )
  {
    temp = *p;
    *p = *q;
    *q = temp;
  }
}



沒有留言:

張貼留言