【发布时间】:2011-04-13 09:16:29
【问题描述】:
我遇到了一些问题。
我需要写一些像memcpy(void*, const void*)这样的函数,它的签名应该是:
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len)
我注意到,在 memcpy 的许多实现中,我们将 void* 转换为 char*,但我认为这不是我的情况,因为 arrayCopy 函数需要用于多种类型的数组,包括structs.
那么,我该怎么做呢?
编辑: 源代码可能是这样的:
#include <stdio.h>
#include <string.h>
void arrayCopy(void *, int, const void *, int, int, size_t);
int main(void)
{
int i;
int dest[10] = {1};
int src [] = {2, 3, 4, 5, 6};
arrayCopy(dest, 1, src, 0, 5, sizeof(int));
for (i=0; i<10; i++) printf("%i\n", dest[i]);
return 0;
}
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len, size_t size)
{
char *cdest = (char*) dest;
const char *csrc = (char*) src;
int i;
len *= size;
if (dest == src)
{
printf("Same array\n");
}else
{
cdest += (dIndex * size);
csrc += (sIndex * size);
for (i=0; i<len; i++)
*cdest++ = *csrc++;
}
}
谢谢。
【问题讨论】:
标签: c generics memcpy void-pointers