在c中交换任何类型的两个变量
c 中是否有任何逻辑可以交换任何类型的两个变量.即 int、float、字符序列.
Is there any logic in c which can swap any type of two variables. i.e int, float, sequence of character.
我可以想到将每种类型的变量存储为字符序列并像普通字符串一样交换它的逻辑,但我不是它的好主意.
I can think of a logic of storing every type of variables as sequence of characte and swap it like normal string but i does not its good idea.
让我们看看如何为两个 char
变量执行此操作.你会做这样的事情.
Let's see how you'd do this for two char
variables. You'd do something like this.
void swap(char* a, char* b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
对于两个 int
变量:
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
等等.现在,为了迎合任何类型的变量,您可能会尝试这样做:
And so on. Now, for catering to any type of variable, you'd be tempted to do:
void swap(void* a, void* b)
{
// ...
}
但是您需要分配一个参数化大小的空间.因此,您必须首先接收该大小作为参数:
But you'd need to allocate a space of a parameterized size. So, you'll have to first receive that size as a parameter:
void swap(void* a, void* b, size_t s)
{
// ...
}
...您将使用 sizeof
表达式将其作为参数传递.您需要分配所述空间并使用它进行分配(副本).在我的脑海里,malloc
/free
和 memcpy
浮现在我的脑海中,所以这是一种粗略的方法来做我们上面为 char
和 int
,但这次使用参数化大小,将是:
...which you'll pass as an argument using a sizeof
expression. And you'll need to allocate said space and do assignments (copies) using that. Off the top of my head, malloc
/free
and memcpy
come to mind, so a crude way to do what we did above for char
and int
, but this time with a parameterized size, would be:
void swap_any(void* a, void* b, size_t s){
void* tmp = malloc(s);
memcpy(tmp, a, s);
memcpy(a, b, s);
memcpy(b, tmp, s);
free(tmp);
}
正如我所描述的,这有点粗糙.您可以尝试使用 alloca
(在堆栈上分配)而不使用 free
.
As I described, this is a little crude. You could try doing it with alloca
(which allocates on the stack) and no free
.
或者,您可以使用宏来实现,因为您可以将 type(而不是 size_t
)传递给宏 - 因为宏本质上使用文本替换来工作.然后,您显然可以按名称创建临时变量类型,如下所示:
Alternatively, you could do it with a macro, since you can pass a type (instead of a size_t
) to a macro - because macros essentially work using text replacement. Then, you can obviously create the temporary variable type by name, like this:
#define swap_m(a, b, t) { t tmp = a; a = b; b = tmp; }
显然,如果您根本不想传递有关所涉及类型的任何信息,则必须对此更有创意.
Obviously, if you don't want to pass any information at all about the involved types, you'd have to be more creative about it.