使用 memcpy 交换未定义大小的值

Swapping values of undefined size with memcpy

我正在尝试交换数组中两个元素的值,我知道它们的大小是一个变量,我的代码如下所示:

void function(void *array, size_t size) {
    /*in this example the array's members are 2
    and i want to swap them*/
    void *help = malloc(size);

    memcpy(help, &array[0], size);
    memcpy(&array[0], &array[1], size);
    memcpy(&array[1], help, size);
    free(help);
}

我是不是漏了什么?

类型void是不完整的类型。所以你不能取消引用 void *.

类型的指针

把函数写成

void function(void *array, size_t size) {
    /*in this example the array's members are 2
    and i want to swap them*/
    void *help = malloc(size);

    memcpy(help, array, size);
    memcpy( array, ( char * )array + size, size);
    memcpy( ( char * )array + size, help, size);
    free(help);
}

这是一个演示程序。

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

void function(void *array, size_t size) {
    /*in this example the array's members are 2
    and i want to swap them*/
    void *help = malloc(size);

    memcpy(help, array, size);
    memcpy( array, ( char * )array + size, size);
    memcpy( ( char * )array + size, help, size);
    free(help);
}

int main(void) 
{
    int a[] = { 1, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    function( a, sizeof( int ) );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    return 0;
}

它的输出是

1 2 
2 1