0

関数を書く必要がある

void reverse(void *base, int nel, int width) 
{ 
    // ... 
}

ここで、base は配列の先頭へのポインター、nel は配列内の要素の数、width は各要素のサイズ (バイト単位) です。

たとえば、配列の最初の 2 つの要素を交換するにはどうすればよいでしょうか?

4

2 に答える 2

2

memcpyvalueの助けを借りて、(多くのコンパイラに組み込まれているため)単純に使用できwidthます。一時変数も必要です。

/* C99 (use `malloc` rather than VLAs in C89) */
#include <string.h>

void reverse(void *base, size_t nel, size_t width) 
{
    if (nel >= 2) {
        char *el1 = base;
        char *el2 = (char *)base + width;
        char tmp[width];

        memcpy(tmp, el1, width);
        memcpy(el1, el2, width);
        memcpy(el2, tmp, width);
    }
}
于 2012-10-10T14:31:53.107 に答える
2

If you you want it type generic, use

void swap(void *base, int len, int width)
{
    void *p = malloc(width);

    memcpy(p,base,width);
    memcpy(base,(char*)base+width,width);
    memcpy((char*)base+width,p,width);

    free(p);
}

This will swap the first 2 elements.

于 2012-10-10T14:32:40.813 に答える