C语言:交换两个任意类型变量的值

一种方法是用宏模仿函数

#define MY_SWAP(type, lhs,  rhs)  do{type temp = lhs;  lhs = rhs;  rhs = temp;}while{false}

一种方式是用void *

int swap(void * lhs, void * rhs, size_t sz)
{
	void * temp = malloc(sz);
	if ( !temp )
		return -1;
	
	memcpy(temp, lhs, sz);
	memcpy(lhs, rhs, sz);
	memcpy(rhs, temp, sz);
	
	free(temp);
	
	return 0;
}

例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "swapAnyThing.h"

void swapAnyThing(void *a, void *b, size_t val_size);

typedef struct {
  char c;
  double x;
  double y;
} Coordinate;

void printCoordinate(Coordinate pos) {
  printf("Pos %c\n", pos.c);
  printf("x: %lf, y: %lf\n", pos.x, pos.y);
}

int main() {
  int a = 0, b = 0;
  float c = 0, d = 0;
  Coordinate pos1, pos2;
  
  // Input
  scanf("%d%d", &a, &b);
  scanf("%f%f", &c, &d);
  scanf(" %c %lf%lf", &(pos1.c), &(pos1.x), &(pos1.y));
  scanf(" %c %lf%lf", &(pos2.c), &(pos2.x), &(pos2.y));
  
  // Print Initial
  printf("Initial\n\n");
  printf("a = %d, b = %d\n", a, b);
  printf("c = %f, d = %f\n", c, d);
  printCoordinate(pos1);
  printCoordinate(pos2);

  // Swap
  swapAnyThing(&a, &b, sizeof(int));
  swapAnyThing(&c, &d, sizeof(float));
  swapAnyThing(&pos1, &pos2, sizeof(Coordinate));
  
  // Print Value after swapping
  printf("\nAfter Swapping\n\n");
  printf("a = %d, b = %d\n", a, b);
  printf("c = %f, d = %f\n", c, d);
  printCoordinate(pos1);
  printCoordinate(pos2);

  return 0;
}

void swapAnyThing(void *a, void *b, size_t val_size)
{
	void *temp = malloc(val_size);
	
	memcpy(temp, a, val_size);
	memcpy(a, b, val_size);
	memcpy(b, temp, val_size);
	free(temp);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值