如何填写使用空白通用指针值的数组? [英] How to fill an array with a value using void generic pointers?

查看:206
本文介绍了如何填写使用空白通用指针值的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于下面的方法

void fillArray(void *arr, int const numElements, void *val, int size)

你怎么能填充数组( *改编)用一个值( * VAL )不知道是什么类型数组? numElements个是在数组中和大小的任何类型的阵列的字节大小的元素数。

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.

推荐答案

您可以使用的memcpy 为。然而,为了推进存储位置,你必须输入指针第一转换为的char *。如果你有无效* ,指针运算没有定义。

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);
   }
}

这篇关于如何填写使用空白通用指针值的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆