How to fill an array with a value using void generic pointers?

僤鯓⒐⒋嵵緔 提交于 2019-12-23 20:40:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!