void* generic pointer

The following code is wrong. I am trying to write a simple generic function using C language syntax,then invoke that function from main(). My goal is to be able to change the data types of Array[] and val without changing the initializearray().If it is doable,please help me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

void initializearray( void* arr[], size_t maxsize, void* value)
{
    int i;
    for(i = 0; i < maxsize; i++)
        arr[i] = *value;
}

int main()
{
    int Array[5],i,val = 1;
    initializearray(Array, 5, &val);
    for(i =0 ; i < 5; i++)
        printf("%d ",Array[i]);
}
Last edited on
void initializearray( void* arr[], size_t maxsize, void* *value)

I think i found the mistake. I wa missing one * symbol in the 3rd parameter in the function prototype..
It works for integers but it crashes for char data type
Last edited on
1
2
3
4
5
6
7
8
9
void fill_array( void* array, size_t array_sz, size_t element_sz, const void* ptr_value )
{
    if( array != NULL && ptr_value != NULL )
    {
        char* bytes = array ;
        for( size_t i = 0 ; i < array_sz ; ++i )
            memcpy( bytes + i*element_sz, ptr_value, element_sz ) ;
    }
}

http://rextester.com/GNGHF8383
Topic archived. No new replies allowed.