user3499639
user3499639

Reputation: 35

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

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.

Upvotes: 3

Views: 2122

Answers (1)

R Sahu
R Sahu

Reputation: 206667

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

Upvotes: 7

Related Questions