使用memcpy和void *交换函数

时间:2015-10-12 18:33:09

标签: c memcpy void-pointers

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

void swap (void *vp1, void *vp2, const size_t size) {
    char *buffer = (char *)malloc(sizeof(char)*size);
    memcpy(buffer, vp1, size);
    memcpy(vp1, vp2, size);
    memcpy(vp2, buffer, size);
    free(buffer);
}

int main()
{
    char *puppy = strdup("Wow");
    char *kitty = strdup("Mew");

    printf("%s, %s\n", puppy, kitty);
    swap(&puppy, &kitty, sizeof(char **));
    printf("%s, %s\n", puppy, kitty);

    free(puppy);
    free(kitty);

    return 0;
}

我正在尝试使用void*memcpy()进行练习。在这段代码中,我首先想到swap(puppy, kitty, sizeof(char *));它有效。但我不明白用法swap(&puppy, &kitty, sizeof(char **));有人可以解释第二次交换的工作原理吗?

1 个答案:

答案 0 :(得分:2)

以下两行:

char *puppy = strdup("Wow");
char *kitty = strdup("Mew");

内存使用情况如下所示:

puppy
+-----------+      +---+---+---+-----+
| address1  |  ->  | W | o | w | \0  |
+-----------+      +---+---+---+-----+

kitty
+-----------+      +---+---+---+-----+
| address2  |  ->  | M | e | w | \0  |
+-----------+      +---+---+---+-----+

您可以实现交换方式:

交换方法1:更改指针的值。

puppy
+-----------+      +---+---+---+-----+
| address2  |  ->  | M | e | w | \0  |
+-----------+      +---+---+---+-----+

kitty
+-----------+      +---+---+---+-----+
| address1  |  ->  | W | o | w | \0  |
+-----------+      +---+---+---+-----+

交换方法2:更改指针指向的内容:

puppy
+-----------+      +---+---+---+-----+
| address1  |  ->  | M | e | w | \0  |
+-----------+      +---+---+---+-----+

kitty
+-----------+      +---+---+---+-----+
| address2  |  ->  | W | o | w | \0  |
+-----------+      +---+---+---+-----+

如果您想要第一种方法的行为,您需要使用:

swap(&puppy, &kitty, sizeof(char*));

如果您想要第二种方法的行为,则需要使用:

swap(puppy, kitty, strlen(puppy));

请记住,如果字符串长度不同,第二种方法将会出现问题。