関数を書く必要がある
void reverse(void *base, int nel, int width)
{
// ...
}
ここで、base は配列の先頭へのポインター、nel は配列内の要素の数、width は各要素のサイズ (バイト単位) です。
たとえば、配列の最初の 2 つの要素を交換するにはどうすればよいでしょうか?
memcpy
valueの助けを借りて、(多くのコンパイラに組み込まれているため)単純に使用でき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);
}
}
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.