交换变量

#include <stdio.h>

// 交换变量
void swap(void *m, void *n, int size);

int main(void) {
  /*
   * 定义两个变量,要求交换变量中记录的值
   * 注意:交换的代码写在一个新的函数swap中
   * */
  int num1, num2;

  printf("输出两个数字:");
  scanf("%d %d", &num1, &num2);

  printf("调用前:%d %d\n", num1, num2);
  swap(&num1, &num2, sizeof(num1));
  printf("调用后:%d %d\n", num1, num2);

  return 0;
}

void swap(void *p1, void *p2, int size) {
  char *pc1 = p1;
  char *pc2 = p2;
  char temp = 0;

  for (int i = 0; i < size; i++, pc1++, pc2++) {
    temp = *pc1;
    *pc1 = *pc2;
    *pc2 = temp;
  }
}
posted @ 2026-01-15 23:29  Zhuye_inking  阅读(1)  评论(0)    收藏  举报