问题
Given the following method
void fillArray(void *arr, int const numElements, void *val, int size)
How can you fill an array (*arr
) with a value (*val
) without knowing what type the array ? numElements
is the number of elements that are in the array and size is the byte size of whatever type the array is.
回答1:
You can use memcpy
for that. However, in order to advance the memory location, you have to cast input pointer to a char*
first. If you have void*
, the pointer arithmetic operations are not defined.
void fillArray(void *arr, int const numElements, void *val, int size)
{
char* cp = arr;
int i = 0;
for ( ; i < numElements; ++i, cp += size )
{
memcpy(cp, val, size);
}
}
来源:https://stackoverflow.com/questions/22872419/how-to-fill-an-array-with-a-value-using-void-generic-pointers